Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c# - How properly inject HttpContext in MVC6

My data service layer in my API required information that are of the request in the httpcontext, I read this question and they said that I should used the ActionContext instead of HttpContext.Current (discontinue in MVC6).

The first way is to set the data inside the controller by overriding this method:

public void OnActionExecuting(ActionExecutingContext context)
{
    var routeData = context.RouteData;
    var httpContext = context.HttpContext;
    ...
}

Or using DI by injecting into the service layer

public MyService(IContextAccessor<ActionContext> contextAccessor)
{
    _httpContext = contextAccessor.Value.HttpContext;
    _routeData = contextAccessor.Value.RouteData;
}

but I'm not sure with of the both line of code listed below is correct way to do the DI

services.AddTransient<IContextAccessor<ActionContext>,ContextAccessor>();
services.AddTransient<IContextAccessor<ActionContext>>();

when I do this I get this error.

Unable to resolve service for type 'Microsoft.AspNet.Mvc.ActionContext' while attempting to activate

Update project.json web project

"DIMultiTenan.Infrastructure": "",
"DIMultiTenan.MongoImplementation": "", 
"Microsoft.AspNet.Server.IIS": "1.0.0-beta3",
"Microsoft.AspNet.Mvc": "6.0.0-beta3",
"Microsoft.AspNet.StaticFiles": "1.0.0-beta3",
"Microsoft.AspNet.Server.WebListener": "1.0.0-beta3"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are trying to access HttpContext, then you can use IHttpContextAccessor for this purpose.

Example:

services.AddTransient<QueryValueService>();

public class QueryValueService
{
    private readonly IHttpContextAccessor _accessor;

    public QueryValueService(IHttpContextAccessor httpContextAccessor)
    {
        _accessor = httpContextAccessor;
    }

    public string GetValue()
    {
        return _accessor.HttpContext.Request.Query["value"];
    }
}

Note that in the above example QueryValueService should be registered only as Transient or Scoped and not Singleton as HttpContext is per-request based...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...