Business Logic Layer - Getting the Current User

六眼飞鱼酱① 提交于 2019-12-13 06:57:40

问题


I have a business logic layer and 2 applications which use this, a MVC UI and a Web API project.

One of the properties on my classes is CreatedBy and UpdatedBy, which should hold the userid.

    public Nullable<System.DateTime> CreatedTS { get; set; }
    public string CreatedBy { get; set; }
    public Nullable<System.DateTime> UpdatedTS { get; set; }
    public string UpdatedBy { get; set; }

Given there are multiple consumers of the BLL what is the best way to capture the userId?

A) - Set this within the BLL using Environment.UserName?

B) - Ask the client to set it and use model data annotation to make this Required

C) - Ask the client to pass this into any Create or Update methods in the BLL.


回答1:


If you're using FormsAuthentication in both MVC and WebApi, you can access properties User.Identity.Name.

int userId = db.Users.Single(r=>r.Name == User.Identity.Name);

In WebApi it will be HttpContext.Current.User.Identity.Name

This approach is quite secure. If you store userId on client-side, user will be able to modify it.




回答2:


I would generally use Thread.CurrentPrincipal.Identity.Name.

To do so, you must ensure that Thread.CurrentPrincipal is set to a principal representing the current user. This is done in the UI tier, and will happen automagically if you:

  • Use a RoleProvider in an ASP.NET application.

  • Use a RoleProvider in a WCF application by setting principalPermissionMode ="UseAspNetRoles".

  • Call AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal); in a client application.



来源:https://stackoverflow.com/questions/27636529/business-logic-layer-getting-the-current-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!