在Action Filter上获取用户名

时间:2013-05-20 12:28:42

标签: c# asp.net-web-api action-filter

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

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

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

5 个答案:

答案 0 :(得分:53)

回答迟到但如果您在过滤器中使用HttpActionContext,这是最佳解决方案您可以随时使用它: -

public partial class MainWindow : Window
{
    private TransformGroup _transformGroup;
    private RotateTransform _rotateTrsf;

    public MainWindow()
    {
        InitializeComponent();
        _transformGroup = new TransformGroup();
        _rotateTrsf = new RotateTransform();
        _transformGroup.Children.Add(_rotateTrsf);

        SetupAnimation();

        myRect.RenderTransform = _transformGroup;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        _rotateAnimation.To = Math.Floor(_rotateTrsf.Angle / 45 + 1) * 45;            
        _rotateTrsf.BeginAnimation(RotateTransform.AngleProperty, _rotateAnimation);
        _rotateAnimation.From = _rotateAnimation.To;            
    }

    private void SetupAnimation()
    {           
        _rotateAnimation = new DoubleAnimation();
        _rotateAnimation.From = 0.0;
        _rotateAnimation.To = 45;
        _rotateAnimation.Duration = new Duration(TimeSpan.FromSeconds(0.3));
    }
}

答案 1 :(得分:32)

你可以尝试

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

首先检查经过身份验证的用户:

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

尝试使用

HttpContext.Current.User.Identity.Name

希望它适合你

答案 2 :(得分:1)

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

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

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

答案 3 :(得分:0)

这就是你需要的

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

答案 4 :(得分:0)

 HttpContext.Current.User.Identity.Name