繁体   English   中英

Httpcontext.current在控制器外部为null

[英]Httpcontext.current is null outside of controller

登录时,我获得的每个用户都会获得一个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();
    }
}

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

https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/getting-started/lifecycle-of-an-aspnet-mvc-5-application/_static/lifecycle-of-an-aspnet-mvc- 5-应用程序1.pdf

一个简单的解决方案是将身份作为参数解析到您的辅助方法中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM