WebApi ActionFilterAttribute,HttpActionContext访问用户名(IPrincipal)

lap*_*sus 10 authentication iprincipal actionfilterattribute asp.net-web-api

我需要在我的动作过滤器中访问当前登录的用户.身份由DelegatingHandler进一步的执行链设置.

可以访问当前IPrincipal使用HttpContext.Current.User. 到目前为止,我避免使用HttpContext.Current,因为在我看来是坏风格.首先,你的代码只有在IIS中托管时才能工作,其次它包含一个System.Web我认为不会受到伤害的引用,但System.Net.Http如果可能的话,我更愿意坚持使用. 依靠好的旧" HttpContext" 感觉不对.

有没有其他方法可以访问用户的身份ActionFilter?或者,HttpContext如果您不打算运行自托管应用程序,是否可以使用?

lap*_*sus 17

我忽视了显而易见的事实.我没有意识到里面有一个Controller属性ControllerContext.

var username = ((ApiController)context.ControllerContext.Controller).User.Identity.Name;
Run Code Online (Sandbox Code Playgroud)

  • 在Web API v2`actionContext.RequestContext.Principal`中可以解决这个问题. (15认同)