【问题标题】:MVC 4 override AuthorizeAttribute not workingMVC 4 覆盖 AuthorizeAttribute 不起作用
【发布时间】:2013-03-04 01:41:12
【问题描述】:

我创建了一个基本的 MVC 4 项目。添加了 HomeController 和 Home\Index.cshtml 和 ContactUs.cshtml。 在 Global.asax 中为 ContactUs 添加路由。

添加一个文件夹 Auth 并在 Auth 文件夹中添加一个类 Auth.css。

using System;
using System.Web;
using System.Web.Http;
using System.Net.Http;


namespace MvcApplicationTestProject1
{
    public class AuthAttribute : AuthorizeAttribute
    {
        //public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        //{
        //    HandleUnauthorizedRequest(actionContext);
        //}        

        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Redirect);
            response.Headers.Add("Location", "http://www.google.com");
            actionContext.Response = response;
        }
        //MVC 4 Web.Http.AuthorizeAttribute has IsAuthorized function but not AuthorizeCore
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            return false;
        }
    }
}

在 HomeController 中

public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        //
        // GET: /Home/  
        [Auth]       
        public ActionResult ContactUs()
        {
            return View();
        }
    }

问题是当运行代码并访问 http://localhost:[port number here]/Home/ContactUs, 它没有命中覆盖类 AuthAttribute。

代码有问题吗?

【问题讨论】:

  • 你想达到什么目的?它不明显......
  • 我正在尝试将 [Authorize] 自定义为 [Auth] 并在 cotrollers 上使用它。这将为我构建自己的身份验证提供灵活性,而不是使用标准成员资格。
  • 这是我试图实现的。唯一的区别是它是 MVC 4 而不是 MVC3。 weblogs.asp.net/jgalloway/archive/2012/05/04/…

标签: asp.net-mvc-4 authorize-attribute


【解决方案1】:

您的评论说您正在尝试实现 this post 中的内容,但您根本不是从该帖子中复制代码,而是从之前的 SO 帖子中复制代码:Using custom authorization in MVC 4 指的是 Web API。在阅读该帖子时,您会发现不同之处在于您使用的 AuthorizeAttribute 。您使用的是System.Web.Http 而不是System.Web.Mvc

如果您使用了您在评论中提到的代码,那么您会发现它会起作用:

using System.Web;
using System.Web.Mvc;

namespace MvcApplicationTestProject1
{
    public class AuthAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            return false;
        }
    }
}

【讨论】:

  • 非常感谢。现在触发了。感谢您的帮助。
  • @user2130167 NP。快乐编程。
  • 哇!谢谢你。
  • 谢谢!荒谬的是,包含不同的命名空间将我指向 mvc4 的错误覆盖,它只是不“工作”并且静默失败。
  • @MikeSmithDev 五年后,仍然相关。如果有某种警告就好了。
猜你喜欢
  • 1970-01-01
  • 2018-01-20
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-03-24
  • 2014-04-03
  • 1970-01-01
相关资源
最近更新 更多