Httpcontext.current在控制器之外为null

时间:2017-03-15 23:22:41

标签: c# asp.net-identity

在登录我收到的每个用户时,会获得一个CompanyId作为索赔。我可以毫无问题地在WebApiController中达到这个要求。但是如果我尝试在控制器方法之外到达它,那么HttpContext.Current变为null。

如何在控制器之外达成我的声明,或者我应该使用哪种解决方案来处理我的身份识别?

public class ProductsController : ApiController
{
    private readonly ProductRepository _productRepo = new ProductRepository();
    private readonly string companyId = MiniHelper.GetCompanyId();

    [Route("ProductList")]
    [EnableQuery()]
    public IQueryable<Product> GetProductList()
    {
        return _productRepo.GetProducts().AsQueryable().Where(u => u.UserId == companyId);
    }
}

public static class MiniHelper
{
    public static string GetCompanyId()
    {
        var identity = (ClaimsIdentity)HttpContext.Current.User.Identity;
        if (identity == null)
            return string.Empty;
        return identity.Claims.Where(a => a.Type == "CompanyId").Select(v => v.Value).FirstOrDefault();
    }
}

1 个答案:

答案 0 :(得分:1)

HttpContext.Current为null,因为您尝试从HttpApplication处理管道中访问它。

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/lifecycle-of-an-aspnet-mvc-5-application/_static/lifecycle-of-an-aspnet-mvc-5-application1.pdf

一个简单的解决方案是将标识解析为辅助方法作为参数。