微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – ASP.NET MVC3 ActionFilterAttribute注入?

嘿,我已经成功地可以在我的Filterattribute中使用属性注入,但是我想知道是否可能将它移动到构造函数中?

我当前的代码

// AuthAttribute.cs

public class AuthAttribute : ActionFilterattribute
{
    public Roles _authRoles { get; private set; }

    [Inject]
    private readonly IAuthorizationService _service;

    public AuthAttribute(Roles roles)
    {
        _authRoles = roles;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
            string redirectUrl = string.Format("?returnUrl={0}",redirectOnSuccess);
            string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;

            filterContext.HttpContext.Response.Redirect(loginUrl,true);
        }
        else
        {
            bool isAuthorized = _service.Authorize(GetUserSession.Id,_authRoles.ToString());

            if (!isAuthorized)
            {
                // Todo: Make custom "Not Authorized" error page.
                throw new UnauthorizedAccessException("No access");
            }
        }
    }
}
// TestController.cs

[Auth(Roles.Developer)]
public ActionResult Index()
{
    // Some smart logic
}

提前致谢!

解决方法

不,这不可能作为构建器 must be simple types的参数.

为了测试的目的,您可以使用另一个构造函数(因为您不应该在测试中使用IoC容器):

public class AuthAttribute : ActionFilterattribute
{
    public Roles _authRoles { get; private set; }

    [Inject]
    private readonly IAuthorizationService _service;

    public AuthAttribute(Roles roles)
    {
        _authRoles = roles;
    }

    public AuthAttribute(Roles roles,IAuthorizationService authSvc)
        : this(roles)
    {
        this.service = authSvc;
    }

    // ...
}

原文地址:https://www.jb51.cc/csharp/93201.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐