Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How properly inject HttpContext in MVC6

Tags:

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" 
like image 249
Son_of_Sam Avatar asked Mar 10 '15 17:03

Son_of_Sam


1 Answers

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

like image 108
Kiran Avatar answered Oct 20 '22 10:10

Kiran