C# 在操作过滤器上获取用户名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16649551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:33:33  来源:igfitidea点击:

Get User Name on Action Filter

c#asp.net-web-apiaction-filter

提问by TamarG

I use MVC4 web application with Web API. I want to create an action filter, and I want to know which user (a logged-in user) made the action. How can I do it?

我使用带有 Web API 的 MVC4 Web 应用程序。我想创建一个操作过滤器,我想知道哪个用户(登录用户)执行了该操作。我该怎么做?

public class ModelActionLog : ActionFilterAttribute
{
    public override void OnActionExecuting(SHttpActionContext actionContext)
    {
       string username = ??
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       ??
    }
}

采纳答案by Rahul

You can try

你可以试试

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
           string username = HttpContext.Current.User.Identity.Name;
        }

Check for authenticated user first:

首先检查认证用户:

string userName = null;
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
    userName = HttpContext.Current.User.Identity.Name;
}

Try to use

尝试使用

HttpContext.Current.User.Identity.Name

Hope it works for you

希望这对你有用

回答by YuriG

This is what you need

这就是你需要的

string username = filterContext.HttpContext.User.Identity.Name;

回答by TamarG

 HttpContext.Current.User.Identity.Name

回答by Morten Christiansen

Perhaps not the prettiest solution, but for Web API ActionFilter you can do the following:

也许不是最漂亮的解决方案,但对于 Web API ActionFilter,您可以执行以下操作:

var controller = (actionContext.ControllerContext.Controller as ApiController);
var principal = controller.User;

Of course, this only applies if your controllers actually inherit from ApiController.

当然,这仅适用于您的控制器实际上是从 ApiController 继承的。

回答by Atul Chaudhary

Bit late for an answer but this is best solution if you are using HttpActionContext in your filter You can always use it as mentioned here:-

答案有点晚,但如果您在过滤器中使用 HttpActionContext,这是最好的解决方案您可以随时使用它,如下所述:-

public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
   if (actionContext.RequestContext.Principal.Identity.IsAuthenticated)
   {
      var userName = actionContext.RequestContext.Principal.Identity.Name;
   }
}