https://github.com/skybrud/skybrud.essentials.aspnetcore
Skybrud.Essentials addon for working with ASP.NET Core.
https://github.com/skybrud/skybrud.essentials.aspnetcore
asp-net asp-net-core limbo net5 nuget package skybrud skybrud-essentials
Last synced: 4 months ago
JSON representation
Skybrud.Essentials addon for working with ASP.NET Core.
- Host: GitHub
- URL: https://github.com/skybrud/skybrud.essentials.aspnetcore
- Owner: skybrud
- License: mit
- Created: 2021-12-13T17:19:20.000Z (over 4 years ago)
- Default Branch: v1/main
- Last Pushed: 2025-04-24T21:27:01.000Z (about 1 year ago)
- Last Synced: 2025-08-22T08:26:39.477Z (10 months ago)
- Topics: asp-net, asp-net-core, limbo, net5, nuget, package, skybrud, skybrud-essentials
- Language: C#
- Homepage:
- Size: 611 KB
- Stars: 0
- Watchers: 4
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Skybrud.Essentials.AspNetCore
[](LICENSE.md)
[](https://www.nuget.org/packages/Skybrud.Essentials.AspNetCore)
[](https://www.nuget.org/packages/Skybrud.Essentials.AspNetCore)
[](https://packages.limbo.works/skybrud.essentials.aspnetcore/)
**Skybrud.Essentials.AspNetCore** is an add-on that builds on top of our [Skybrud.Essentials](https://github.com/skybrud/Skybrud.Essentials) package, and it provides various logic that makes it easier to work with different parts of ASP.NET Core - eg. parsing query strings and reading request headers..
License:
MIT License
Target Frameworks:
.NET 5, .NET 6 and .NET 7
## Installation
### NuGet
To install the package via [**NuGet**](https://www.nuget.org/packages/Skybrud.Essentials.AspNetCore), you can use either .NET CLI:
```
dotnet add package Skybrud.Essentials.AspNetCore
```
or the NuGet package manager:
```
Install-Package Skybrud.Essentials.AspNetCore
```
## Examples
### Extension methods for `HttpRequest`
```cshtml
@using Microsoft.AspNetCore.Http
@using Skybrud.Essentials.AspNetCore
@inject IHttpContextAccessor HttpContextAccessor
@{
HttpRequest request = HttpContextAccessor.HttpContext.Request;
Uri uri = request.GetUri();
Scheme: @uri.Scheme
Host: @uri.Host
Port: @uri.Port
PathAndQuery: @uri.PathAndQuery
ToString: @uri.ToString()
Authority: @uri.GetLeftPart(UriPartial.Authority)
PathAndQuery: @uri.PathAndQuery
Remote Address: @request.GetRemoteAddress()
Accept Types: @request.GetAcceptTypes()
Accept Encoding: @request.GetAcceptEncoding()
Accept Languages: @request.GetAcceptLanguage()
User Agent: @request.GetUserAgent()
Referrer: @request.GetReferrer()
}
```
### Extension methods for `IQueryCollection`
#### Strings
```cshtml
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Primitives
@using Skybrud.Essentials.AspNetCore
@{
IQueryCollection query = new QueryCollection(new Dictionary {
{"id", new StringValues("1")},
{"ids", new StringValues(new []{"1", "2", "3"})},
{"moreIds", new StringValues(new []{"5,6", "7", "8"})}
});
// Prints "1"
string? id = query.GetString("id");
@id
// Prints "1,2,3"
string[] ids = query.GetStringArray("ids");
@string.Join(",", ids)
// Prints "5,6,7,8"
List moreIds = query.GetStringList("moreIds");
@string.Join(",", moreIds)
// Prints "'nope' not found"
if (query.TryGetString("nope", out string? nope)) {
@nope
} else {
'nope' not found.
}
}
```
#### Int32
```cshtml
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Primitives
@using Skybrud.Essentials.AspNetCore
@{
IQueryCollection query = new QueryCollection(new Dictionary {
{"id", new StringValues("1")},
{"ids", new StringValues(new []{"1", "2", "3"})},
{"moreIds", new StringValues(new []{"5,6", "7", "8"})}
});
// Prints "1"
int id = query.GetInt32("id");
@id
// Prints "2" (via fallback)
int id2 = query.GetInt32("id2", 2);
@id2
// Prints "" (since null is rendered as empty)
int? id3 = query.GetInt32OrNull("id3");
@id3
// Prints "1,2,3"
int[] ids = query.GetInt32Array("ids");
@string.Join(",", ids)
// Prints "5,6,7,8"
List moreIds = query.GetInt32List("moreIds");
@string.Join(",", moreIds)
// Prints "'nope' not found"
if (query.TryGetInt32("nope", out int? nope)) {
@nope
} else {
'nope' not found.
}
}
```
#### Int64
```cshtml
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Primitives
@using Skybrud.Essentials.AspNetCore
@{
IQueryCollection query = new QueryCollection(new Dictionary {
{"id", new StringValues("1")},
{"ids", new StringValues(new []{"1", "2", "3"})},
{"moreIds", new StringValues(new []{"5,6", "7", "8"})}
});
// Prints "1"
long id = query.GetInt64("id");
@id
// Prints "2" (via fallback)
long id2 = query.GetInt64("id2", 2);
@id2
// Prints "" (since null is rendered as empty)
long? id3 = query.GetInt64OrNull("id3");
@id3
// Prints "1,2,3"
long[] ids = query.GetInt64Array("ids");
@string.Join(",", ids)
// Prints "5,6,7,8"
List moreIds = query.GetInt64List("moreIds");
@string.Join(",", moreIds)
// Prints "'nope' not found"
if (query.TryGetInt64("nope", out long? nope)) {
@nope
} else {
'nope' not found.
}
}
```
#### Float
```cshtml
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Primitives
@using Skybrud.Essentials.AspNetCore
@{
IQueryCollection query = new QueryCollection(new Dictionary {
{"pi", new StringValues("3.14")},
{"values", new StringValues(new []{"3.14", "6.28", "9.42"})},
{"otherValues", new StringValues(new []{"3.14,6.28", "9.42"})}
});
// Prints "3.14"
float pi = query.GetFloat("pi");
@pi
// Prints "1.23" (via fallback)
float meh = query.GetFloat("meh", 1.23f);
@meh
// Prints "" (since null is rendered as empty)
float? meh2 = query.GetFloatOrNull("meh");
@meh2
// Prints "3.14,6.28,9.42"
float[] values = query.GetFloatArray("values");
@string.Join(",", values)
// Prints "3.14,6.28,9.42"
List otherValues = query.GetFloatList("otherValues");
@string.Join(",", otherValues)
// Prints "'nope' not found"
if (query.TryGetFloat("nope", out float? nope)) {
@nope
} else {
'nope' not found.
}
}
```
#### Double
```cshtml
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Primitives
@using Skybrud.Essentials.AspNetCore
@{
IQueryCollection query = new QueryCollection(new Dictionary {
{"pi", new StringValues("3.1415926535")},
{"values", new StringValues(new []{"3.1415926535", "6.283185307", "9.4247779605"})},
{"otherValues", new StringValues(new []{"3.1415926535,6.283185307", "9.4247779605"})}
});
// Prints "3.1415926535"
double pi = query.GetDouble("pi");
@pi
// Prints "1.23" (via fallback)
double meh = query.GetDouble("meh", 1.23);
@meh
// Prints "" (since null is rendered as empty)
double? meh2 = query.GetDoubleOrNull("meh");
@meh2
// Prints "3.1415926535,6.283185307,9.4247779605"
double[] values = query.GetDoubleArray("values");
@string.Join(",", values)
// Prints "3.1415926535,6.283185307,9.4247779605"
List otherValues = query.GetDoubleList("otherValues");
@string.Join(",", otherValues)
// Prints "'nope' not found"
if (query.TryGetDouble("nope", out double? nope)) {
@nope
} else {
'nope' not found.
}
}
```
#### Boolean
```cshtml
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Primitives
@using Skybrud.Essentials.AspNetCore
@{
IQueryCollection query = new QueryCollection(new Dictionary {
{"a", new StringValues("true")},
{"b", new StringValues("1")}
});
// Prints "True"
bool a = query.GetBoolean("a");
@a
// Prints "True"
bool b = query.GetBoolean("b");
@b
// Prints "False"
bool c = query.GetBoolean("c");
@c
// Prints "True" (via fallback)
bool d = query.GetBoolean("d", true);
@d
// Prints "" (since null is rendered as empty)
bool? e = query.GetBooleanOrNull("e");
@e
// Prints "'nope' not found"
if (query.TryGetBoolean("nope", out bool? nope)) {
@nope
} else {
'nope' not found.
}
}
```
### Forcing API controllers to use Newtonsoft.Json
By default, ASP.NET Core uses the logic within the `System.Text.Json` namespace to serialize models to JSON. If you wish to use the `Newtonsoft.Json` package instead, there are a few different approaches for doing so:
#### Use the `Microsoft.AspNetCore.Mvc.NewtonsoftJson` package
This package let's you set up all your API controllers to use `Newtonsoft.Json` for serializing JSON. This is a global setting, so be aware that this may affect parts of your application that it shouldn't.
You don't need `Skybrud.Essentials.AspNetCore` when using this approach.
#### Use the `NewtonsoftJsonResult` class
As an alternative to enabling the use of `Newtonsoft.Json` globally, you can use the `NewtonsoftJsonResult` class from this package. This let's you determine the output an method level - eg. have a controller where some methods use the default `System.Text.Json`, but where others use `Newtonsoft.Json`.
This `NewtonsoftJsonResult` extends ASP.NET Core's `ContentResult` class, and serves as a wrapper for your response body. You may use the `NewtonsoftJsonResult` constructor directly, which then let's you specify a HTTP status code and a value representing your response body. But the class also features a number of static methods for creating a new response with a specific status code:
```csharp
public ActionResult Hello() {
return NewtonsoftJsonResult.Ok(new { yay = true } );
}
```
```csharp
public ActionResult OhNoes() {
return NewtonsoftJsonResult.InternalError("The server made a boo boo.");
}
```
The `NewtonsoftJsonResult.Ok` and `NewtonsoftJsonResult.Created` methods are used for creating successful responses, so they both take a single parameter representing the response body.
On the other hand, the `NewtonsoftJsonResult.BadRequest`, `NewtonsoftJsonResult.Unauthorized`, `NewtonsoftJsonResult.Forbidden`, `NewtonsoftJsonResult.NotFound` and `NewtonsoftJsonResult.InternalError` represent responsens wrapping an error, so they take a single string parameter with an error message.
For instance, the `NewtonsoftJsonResult.InternalError("The server made a boo boo.")` from before will result in a response with a 500 status code and the following JSON body:
```json
{
"meta": {
"code": 500,
"error": "The server made a boo boo."
}
}
```
#### Use `NewtonsoftJsonOnlyConfigurationAttribute` on the controller
If you wish to set this up at the controller level, you can add the `NewtonsoftJsonOnlyConfigurationAttribute` to your API controller:
```csharp
[NewtonsoftJsonOnlyConfiguration]
public class MyController : Controller {
public ActionResult Hello() {
return new { yay = true };
}
}
```