自定义授权属性在mvc中不起作用

时间:2016-08-01 06:35:02

标签: asp.net asp.net-mvc-5

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

namespace BugMesh.Authorize
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CustomAuthorize : AuthorizeAttribute
    {
        BugMesh_Entities db = new BugMesh_Entities();
        private readonly string[] allowedroles;
       public CustomAuthorize(params string[] Roles)
       {  
          this.allowedroles = Roles;  
       }  
       protected override bool AuthorizeCore(HttpContextBase httpContext)  
       {
           bool authorize = false;  
          foreach (var role in allowedroles)  
          {
              var usr = db.Users.Where(m => m.Role == role);
             if (usr.Count() > 0)
             {  
                authorize = true;  
             }  
          }  
          return authorize;  
       }  
       protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)  
       {  
          filterContext.Result = new HttpUnauthorizedResult();
       }  
    }
}

//在UserController索引页面上应用的身份验证
    控制器

[CustomAuthorize("Developer")]
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }`

这一行也写在webconfig文件中。我希望应用身份验证,具有特定角色的用户可以查看特定的视图。我也想知道我可以使用身份验证登录系统,因为我使用了Session [" UserName"]键,但它无效。希望我解释了我的问题。

0 个答案:

没有答案
相关问题