default login url on HttpUnauthorizedResult in asp.net mvc

佐手、 提交于 2019-12-09 16:20:12

问题


I have written a custom AuthorizeAttribute which has the following condition in asp.net mvc3 application:

public override void OnAuthorization(AuthorizationContext filterContext)
{     
    //auth failed, redirect to Sign In
    if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
    {
       filterContext.Result = new HttpUnauthorizedResult();
    }
}

And in my web.config, i have:

<authentication mode="Forms">
  <forms loginUrl="~/User/SignIn" timeout="2880" />
</authentication>

On authentication fail, it redirects to "/Account/Login" page by default.

How do i change this default redirect url and redirect it to "/User/SignIn"?

The screenshot shows the clear view of what i am trying to say..

Though i have set '/User/SignIn', it redirects to '/Account/Login'


回答1:


I am not sure whether i can add this as an answer. But this may help others who were having this related issue.

I got the solution after a struggle. I have added WebMatrix.WebData reference recently, which seems to be the real culprit of this issue. This can be handled by adding the key to your config file:

<add key="loginUrl" value="~/User/SignIn" />



回答2:


You should be modifying the root one for loginUrl.

i have created AuthorizationAttribute... it's redirecting properly e.g.

<authentication mode="Forms">
    <forms loginUrl="~/Authenticate/SignIn" timeout="2880"/>
</authentication>

and my attribute is:

public class AuthorizationAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

and apply attribute to any method of your controller as necessary...

[AuthorizationAttribute()]
public ActionResult Index()
{
    return View();
}



回答3:


I recently had this problem and found it was because I had the WebMatrix.dll referenced in my project.

Removing this DLL fixed the issue

see here What is the PreserveLoginUrl appSetting key/value in an ASP.NET MVC application?



来源:https://stackoverflow.com/questions/6015464/default-login-url-on-httpunauthorizedresult-in-asp-net-mvc

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