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

这个问题在这里已经有一个答案:> Can I access IIdentity from Web API4个
我需要在我的操作过滤器中访问当前登录用户.身份由DelegatingHandler进一步设定执行链.

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

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

解决方法

我忽略了明显的.我没有意识到ControllerContext中有一个Controller属性.
var username = ((ApiController)context.ControllerContext.Controller).User.Identity.Name;

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...