HttpContextExtensions 0.1.3
dotnet add package HttpContextExtensions --version 0.1.3
NuGet\Install-Package HttpContextExtensions -Version 0.1.3
<PackageReference Include="HttpContextExtensions" Version="0.1.3" />
<PackageVersion Include="HttpContextExtensions" Version="0.1.3" />
<PackageReference Include="HttpContextExtensions" />
paket add HttpContextExtensions --version 0.1.3
#r "nuget: HttpContextExtensions, 0.1.3"
#:package HttpContextExtensions@0.1.3
#addin nuget:?package=HttpContextExtensions&version=0.1.3
#tool nuget:?package=HttpContextExtensions&version=0.1.3
<div align="center" style="text-align: center;"> <img src="./logo.png" alt="Logo" /> </div>
Description
HttpContextExtensions
is a C# library that provides useful features for working with HttpContext
in ASP.NET Core. This library simplifies accessing common HTTP context information and manipulating data in web requests.
Compatibility
This lib can be used with .NET 6, 7 and 8
Contributing
Feel free to open issues requesting new features or reporting bugs. For code contributing, fork this project and create a PR to features/your-feature.
Features
- Simplified Access: Methods to access
HttpContext
data more directly and intuitively. - Request and response: Simple access to common items, like headers, cookies, body, method and more.
- Request Tracker: Track requests and responses with automatic GUID.
- IP Filter: Blacklist and Whitelist IPS using a middleware or attributes.
- IP Information: Easy get IP information like ASN and Country with your own implementation.
- Dependency injection: Easy dependency injection support.
Installation
To install the library, you can use the NuGet Package Manager:
dotnet Install-Package HttpContextExtensions
Usage examples
Base usage
builder.Services.AddSingleton(new InspectorOptions().SetIpHeaderName("X-Real-IP")); //SINGLETON OR SCOPPED
builder.Services.AddScoped<IProvider, CustomIpInfoProvider>(); //SINGLETON OR SCOPPED, YOUR CHOICE
builder.Services.AddScoped<IInspector, Inspector>(); //SCOPPED ONLY
IP Header name is optional, and can be configured to get real IP behind proxies like Nginx and CloudFlare.
IP Info Provider is optional too, you need to implement IProvider interface and inject your implementation.
IP Info Provider
public class CustomIpInfoProvider : IProvider
{
public Task<string> GetCountryCode(string ip)
{
return Task.FromResult("BR");
}
public Task<string> GetCountryName(string ip)
{
return Task.FromResult("BRAZIL");
}
public Task<string> GetAsn(string ip)
{
return Task.FromResult("AS12345");
}
public Task<string> GetAsnName(string ip)
{
return Task.FromResult("Telefonica SA");
}
public Task<T> GetData<T>(string ip)
{
var data = MyService.getCustomInfo(ip);
return Task.FromResult(data);
}
}
The provider is a method to get information from ips, you can implement integrations with an IP Intelligence service, like MaxMind, IpToLocation or any other.
GetData can be used to retrieve custom data from your provider.
Blacklist and Withe List
The endpoint will return 403 Forbidden when the IP does not match the rule. Never use Whitelist and Blacklist on the same scope. SetRedirectUrl is optional. Only IPV4 without mask is supported at this time.
Ips Configuration
var blackListIps = new HashSet<string>(["x.x.x.x", "x.x.x.x"]);
builder.Services.AddSingleton<IBlacklistConfiguration>(new BlacklistConfiguration(blackListIps).SetRedirectUrl("https://google.com"));
var whiteListIps = new HashSet<string>(["x.x.x.x", "x.x.x.x"]);
builder.Services.AddSingleton<IWhitelistConfiguration>(new WhitelistConfiguration(whiteListIps).SetRedirectUrl("https://google.com"))
Endpoint based usage
//Endpoint Based
public class MyController : ControllerBase
{
[IpBlacklist]
public IActionResult MyEndpoint1()
{
return Ok();
}
[IpWhitelist]
public IActionResult MyEndpoint2()
{
return Ok();
}
}
Controller based usage
[IpBlacklist]
public class MyController : ControllerBase {}
[IpWhitelist]
public class MyController : ControllerBase {}
Middleware based usage
app.UseIpBlacklist();
app.UseIpWhitelist();
Request tracker
The request tracker will set a GUID on the request and response. The X-Request-Tracker header will be sent on the response.
Tracker configuration
app.UseRequestTracker();
Retrieving Tracker GUID
var guidFromInspector = inspector.For(HttpContext).GetRequestTracker();
var guidFromContext = (Guid) HttpContext.Items["RequestTracker"];
var guidFromHeader = Guid.Parse(HttpContext.Request.Headers["X-Request-Tracker"]);
//RESULT = 47cf1f9f-345e-4864-8b52-10a191d4f3f5
Retrieving basic information
On a controller
public class MyController(IInspector inspector) : ControllerBase
{
public IActionResult MyEndpoint1()
{
inspector.For(HttpContext);
var guid = inspector.GetRequestTracker();
var ipInfo = inspector.GetIpInfo();
var request = inspector.GetRequest();
var response = inspector.GetResponse();
var userAgent = inspector.GetUserAgent();
var ip = inspector.GetIp();
var customData = inspector.GetData<MyIpCustomIndo>();
return Ok();
}
}
On a middleware
public class CustomMiddleware(RequestDelegate next)
{
public async Task InvokeAsync(HttpContext context)
{
var inspector = context.RequestServices.GetService<IInspector>();
inspector.For(context);
//YOUR IMPLEMENTATION
context.Response.OnCompleted(() =>
{
inspector.For(context);
//YOUR IMPLEMENTATION
//RESPONSE IS NOW COMPLETED
return Task.CompletedTask;
});
await next(context);
}
}
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net6.0 is compatible. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 is compatible. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net6.0
- No dependencies.
-
net7.0
- No dependencies.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.