简体   繁体   English

ASP.Net MVC 5-在控制器外部访问HttpContext.Current.User的正确方法?

[英]ASP.Net MVC 5 - Correct way to access HttpContext.Current.User outside of controller?

I have an ASP.NEt MVC 5 application which uses a service to access information about the user. 我有一个ASP.NEt MVC 5应用程序,该应用程序使用服务来访问有关用户的信息。

Currently I pass it as a parameter to the method in the service class or do the following in each method where its required: 目前,我将它作为参数传递给服务类中的方法,或者在需要的每个方法中执行以下操作:

if (HttpContext.Current.User.Identity.IsAuthenticated)
{
        var user = HttpContext.Current.User;

        // do some stuff
}

How can I refactor the code to lets say inject it into the constructor of the class so that its available to any method in the class or is it correct the way i'm doing it at present eg passing it as a parameter? 我如何重构代码,比如说将其注入到类的构造函数中,以便它可用于该类中的任何方法,或者它是否正确修改了我目前的操作方式(例如,将其作为参数传递)?

public class ViewModelBuilderService : IViewModelBuilderService
{
    private readonly IUnitOfWork _unitOfWork;


    public ViewModelBuilderService(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork; 

    }

    // Other methods...

}

First of all why your business layer should at all need to know HttpContext . 首先,为什么您的业务层完全需要了解HttpContext It shouldn't ... in case if at all needed then store the data into a variable and pass it to the method you are calling. 如果根本不需要,则不应该将数据存储到变量中,然后将其传递给您正在调用的方法。 Currently the approach you are following. 当前您正在遵循的方法。

Probably you can try accessing the System.Threading.Thread.CurrentPrincipal in order to get the authentication context 可能您可以尝试访问System.Threading.Thread.CurrentPrincipal以获得身份验证上下文

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

相关问题 ASP.Net Httpcontext.Current.User显示生成线程的最后一个用户 - ASP.Net Httpcontext.Current.User shows last user who spawned thread 在异步等待中使用 HttpContext.Current.User 的正确方法 - Correct way to use HttpContext.Current.User with async await 如何从 ASP.NET mvc 中的 controller 访问 HttpContext - How to access HttpContext from controller in ASP.NET mvc 如何在视图中访问HttpContext.Current.User自定义属性 - How to access HttpContext.Current.User custom attributes in the view 安装.NET Framework 4.5后,HttpContext.Current.User为null - HttpContext.Current.User is null after installing .NET Framework 4.5 在 ASP.NET Core 中访问当前的 HttpContext - Access the current HttpContext in ASP.NET Core HttpContext.Current.User对于无状态会话是否安全? - Is HttpContext.Current.User Safe for Stateless Session? System.Web.HttpContext.Current.get在ASP.NET MVC控制器中返回null - System.Web.HttpContext.Current.get returned null in asp.net mvc controller 将ASP.NET MVC控制器中的当前用户传递给DAL - Pass current user in ASP.NET MVC controller to DAL 鉴于一台服务器上的ASP.Net MVC站点而不是另一台服务器上的HttpContext.Current.User.Identity为空/空 - HttpContext.Current.User.Identity is null/empty in view of ASP.Net MVC site on one server but not the other
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM