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

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

问题描述

嘿,我已经成功地在我的 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?

我当前的代码:

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

提前致谢!

推荐答案

不,这不可能作为构造函数的参数 必须是简单类型.

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天全站免登陆