c# – ASP.NET MVC3 ActionFilterAttribute注入?

前端之家收集整理的这篇文章主要介绍了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.f2er.com/csharp/93201.html

猜你在找的C#相关文章