Share an article about HttpContext in ASP.
Now, trying to build your code around httpcontext.current is really not a good idea, but I think if you're migrating an enterprise-type application, many HttpContext.Current will Around this business logic, it may provide some temporary mitigation of the terms of the porting application. Also, in the past I have written something that I don't necessarily think is a good idea.
Our modern httpcontext.current will depend on parsing the context from Ihttpcontextaccessor , and might look like this:
namespace System.Web
{
public static class HttpContext
{
private static IHttpContextAccessor _contextAccessor;
public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;
internal static void Configure(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
}
}
Note that we even put it in the system.web namespace so that you can make any potential migrations easier.
We just need to add the code to the configure as early as possible in the processing pipeline and pass in the ihttpcontextaccessor. This can be achieved by two extension methods:
public static class StaticHttpContextExtensions
{
public static void AddHttpContextAccessor(this IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app)
{
var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
Common.HttpContext.Configure(httpContextAccessor);
return app;
}
The first one will be called from configureservices at startup and the accessors are registered in Di. We have determined that this is necessary for the default ihttpcontextfactory to properly share its HttpContext instances.
The second one will be called from Configure at startup , and it will ensure that our custom httpcontext.current is given its Ihttpcontextaccessor to make it work properly.
That's it. This is my Startup class, set the table for static httpcontext.current .
public class Startup
{ public void ConfigureServices(IServiceCollectionservices)
{
services.AddHttpContextAccessor();
} public void Configure(IApplicationBuilderapp)
{
app.UseStaticHttpContext();
app.UseMvc();
}
}
Example:
public class MyService
{ public void DoWork()
{
var context=HttpContext.Current; // continue with context instance }
}
Well, this article also solved my long-time confusion, today to share here!
You are welcome to pay attention to my public number, the number of public number of fans, that is, you love my degree!
The magical application of Ihttpcontextaccessor and Httpcontextaccessor in ASP.