1

我正在尝试向我的控制器添加授权,但它不起作用......

我不确定在我的程序中的哪里查看,但添加

[Authorize] 

我的控制器中的过滤器不起作用,更不用说类似的东西了

[Authorize(Roles = "Manager")]

我已经能够在创建新 MVC 项目时提供的默认应用程序中使用它(即,如果我没有登录,我可以将“关于”选项卡重定向到登录屏幕),所以我假设我在构建应用程序的过程中把事情搞砸了。有谁知道我应该在哪里解决这个问题?我有用户,他们有角色;我正在使用自动创建的 ASP.net 架构;我已经上下检查了我的 web.config 文件,虽然我对此很陌生,但似乎没有什么不合适的。我不知道为什么我的授权过滤器不起作用.?。

4

1 回答 1

1

我写了一个自定义属性来解决这个问题。您可以将控制器方法归因于如下:

[RequiresRole(Role="Admin")]
public ActionResult Index()
{
    int i = 5 + 5;

    return View();
}

该属性的代码如下......

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Web.Controllers
{
    public class RequiresRoleAttribute : ActionFilterAttribute
    {
        public string Role { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (string.IsNullOrEmpty(Role))
            {
                throw new InvalidOperationException("No role specified.");
            }

            string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath;
            string redirectUrl = string.Format("?returnUrl={0}", redirectOnSuccess);
            string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.HttpContext.Response.Redirect(loginUrl, true);
            }
            else
            {
                bool isAuthorised = filterContext.HttpContext.User.IsInRole(this.Role);
                if (!isAuthorised)
                {                        
                    filterContext.HttpContext.Response.Redirect(loginUrl, true);
                }                
            }  
        }      
    }
}
于 2010-02-02T15:30:15.287 回答