ASP.NET MVC3 + ActionFilterAttribute +注入? [英] ASP.NET MVC3 + ActionFilterAttribute + Injection?

查看:270
本文介绍了ASP.NET MVC3 + ActionFilterAttribute +注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我succesfull已经能够使用属性注入在我FilterAttribute,但是我想知道它是否可能将其移动到构造呢?

Hey there, I've succesfull been able to use property injection in my FilterAttribute, however I'm wondering whether its possible to move it into the constructor instead?

我目前的code:

// 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
}

在此先感谢!

推荐答案

没有,这是不可能的参数构造函数<一个href=\"http://stackoverflow.com/questions/1235617/how-to-pass-objects-into-an-attribute-constructor\">must简单类型的。

No, this isn't possible as the parameters for the constructors must be simple types.

有关测试的目的,你可以有另一个构造函数(因为你不应该使用与测试IoC容器):

For testing purposes, you could have another constructor (since you shouldn't be using an IoC container with testing):

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;
    }

    // ...
}

这篇关于ASP.NET MVC3 + ActionFilterAttribute +注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆