6

我本来希望它返回“真”或“假”...

我已经在我的控制器中覆盖了 OnAuthorization 并且基于丢失或无效的 HTTP 标头值我想返回 403 禁止,但是我似乎无法弄清楚如何从 OnAuthorization 返回任何内容,以便它实际上会停止控制器的其余部分从运行。

我该怎么办?

我在下面的第一次尝试是一个巨大的失败,我认为 Deny() 正在运行但没有任何反应......

public class AuthController : Controller
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
                Deny();

            string authString = filterContext.HttpContext.Request.Headers["Authorization"];

            base.OnAuthorization(filterContext);
        }

        private ActionResult Deny()
        {
            HttpContext.Response.StatusCode = 403;

            return Content("Access Denied", "text/plain");
        }
    }

UPDATE看起来像这样成功了,为什么这可能是一个不好的方法?

    if (string.IsNullOrEmpty(filterContext.HttpContext.Request.Headers["Authorization"]))
    {
        filterContext.Result = Content("Access Denied", "text/plain");
        filterContext.HttpContext.Response.StatusCode = 403;

        base.OnAuthorization(filterContext);
    }

再次更新好的,所以现在它根本不起作用......我放了一个断点,看着它进入那个 if 语句,然后进入 base.OnAuthorization(...) 调用,然后再次退出......如果它没有执行,为什么它会进入 if 语句?如果它正在执行,为什么调用 base.OnAuthorization(...) 不会提前结束?

4

5 回答 5

8

你可以抛出一个 httpexception:

throw new HttpException(403, "Access Denied");
于 2011-07-28T20:38:01.503 回答
4

关于什么?

throw new UnauthorizedAccessException();
于 2011-09-02T11:16:30.770 回答
1

保护应用程序的另一种方法: 保护您的 ASP.NET MVC 3 应用程序

于 2011-08-17T13:08:56.747 回答
0

如何使用这样的路线:

filterContext.Result.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Message", action = "AccessDenied" }));

:)

于 2014-05-30T02:41:32.980 回答
0

实际上,当为 ActionResult 调用控制器时,页面需要一个 View。您可以实现以下 UI 以便用户更好地理解:

//code for checking whether authorized goes here...//
bool isAuthorised = SomeFunction();
if (!isAuthorised)
{
    var viewData = new ViewDataDictionary();
    viewData.Add("Message", "You do not have sufficient privileges for this operation.");
    filterContext.Result = new ViewResult { ViewName = "Unauthorized", ViewData = viewData };
    //The View "Unauthorized" is merely a View page that could inherit from a master View or none,       
    //and could be situated in your Views\Shared folder.
    //And you can present the message in the View page like this or so: 
    //<div style="color:Red; font-size:12pt; font-weight:bold;"> <%:ViewData["Message"] %></div>
}
return;

视图名称“未授权”可以是您想要的任何名称,它应该是位于共享视图文件夹中的视图。

于 2014-07-08T11:54:22.973 回答