Asp MVC [Authorize] to return a Post instead of a Get

吃可爱长大的小学妹 提交于 2019-12-23 03:45:30

问题


I would like to use [Authorize(Roles="Admin")] tags on my controller methods.

If a user is not an admin I would like to return this user to my login screen. The default behaviour of returning the user to my login page is reroute my user to "Account/Login" using a Get url.

The problem is, my website's subpages are all partial views refreshed by Ajax calls, including my login screen.

So my question is: Is it possible to alter the class below to return a post redirect instead of a get redirect?

public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
  override public void OnAuthorization(AuthorizationContext filterContext)
  {
    base.OnAuthorization(filterContext);
    // Only do something if we are about to give a HttpUnauthorizedResult and we are in AJAX mode.
    if (filterContext.Result is HttpUnauthorizedResult && filterContext.HttpContext.Request.IsAjaxRequest())
    {
      filterContext.Result =  new RedirectResult("../Account/Login");
    }
  }
}

回答1:


Apparently the problem seemes solved by removing the

[Acceptverbs(HttpVerbs.Post)]

attribute on my Account controller's Login method.

This way we don't even have to override the AuthorizeAttribute

:)




回答2:


I found a solution in Microsoft.WebPages.PreApplicationStartCode.SetupFormsAuthentication()

One need only add an appSetting named "loginUrl" to specify the login action:

<add key="loginUrl" value="~/Account/LogOn"/>


来源:https://stackoverflow.com/questions/1206736/asp-mvc-authorize-to-return-a-post-instead-of-a-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!