Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...