How properly inject HttpContext in MVC6

后端 未结 1 1018
栀梦
栀梦 2020-12-09 09:03

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 inst

相关标签:
1条回答
  • 2020-12-09 09:41

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

    0 讨论(0)
提交回复
热议问题