我想授权添加到我的控制器和它不工作...

我不知道在哪里我的程序看,但添加

[Authorize] 

在我的控制器过滤器不能正常工作,让喜欢

[Authorize(Roles = "Manager")]

我已经能够获得在创造一个新的MVC项目时提供的默认应用程序这个工作(即我能做出“关于”选项卡重定向到登录界面,如果我没有登录) ,所以我想我已经搞砸的事情了前进的道路上,因为我已经建立了我的应用程序。有谁知道我应该寻找解决这一问题?我有用户和他们的角色;我使用的是ASP.net模式,它是自动创建的;我检查了我的web.config文件上下,虽然我很新的这一点,似乎没有什么是地方出。我不知道为什么我的授权过滤器工作不?

有帮助吗?

解决方案

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

[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);
                }                
            }  
        }      
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top