Default login url on HttpUnauthorizedResult in asp.net mvc

I wrote a custom AuthorizeAttribute that has the following condition in an 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> 

If an authentication error occurs, it is redirected to the "/ Account / Login" page by default.

How to change this default redirect URL and redirect it to "/ User / SignIn"?

The screenshot shows a clear idea of ​​what I'm trying to say. HttpUnauthorizedresult image

Although I set '/ User / SignIn', it redirects to '/ Account / Login'

+8
authentication asp.net-mvc custom-attributes forms-authentication
source share
3 answers

I am not sure if I can add this as an answer. But it can help others who have had this problem.

I got a solution after a fight. I recently added a WebMatrix.WebData link, which seems to be the real culprit for this problem. This can be handled by adding a key to your configuration file:

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

You must change the root for loginUrl.

I created an AuthorizationAttribute ... it redirects correctly for example.

 <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 the attribute to any method of your controller as needed ...

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

I recently had this problem and found that it was due to the fact that there was a link to WebMatrix.dll in my project.

Removing this dll fixes the problem

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

+1
source

All Articles