In an ASP.NET MVC3 web application, an entire controller has an [Authorize]
attribute attached to it. So if the user is not logged in or the session expired, they get redirected to the login page. This is working...sometimes. The URLs in the "works" list below correctly redirect to the login page; the URLs in the "does not work" list instead show the IIS 401 error screen - they do not redirect to the login page.
Works
Does Not Work
The model for the MyAction
action has a public string ReturnUrl { get; set; }
in its base class. It also has other properties, but adding those to the query string does not affect the login redirection. It seems to be only the ReturnUrl parameter.
I'm not sure what else to look into. Any ideas why the ReturnUrl
parameters would be causing trouble?
Routes
routes.MapRoute("Default-Title-ID", "{Controller}/{Action}/{Title}_{ID}", namespaces);
routes.MapRoute("Default-ID", "{Controller}/{Action}/{ID}", namespaces);
routes.MapRoute("Default", "{Controller}/{Action}", new { Controller = "Home", Action = "Index" }, namespaces);
routes.MapPageRoute("Reports-View", "ViewReport_{ID}", "~/Views/Reports/View.aspx");
Working Example (Well, not working, but illustrates the problem.)
Download the solution here: https://docs.google.com/file/d/0B4o6vqgNLpvbeVo4bVdKZWFMcEE/edit?usp=sharing
And then try to visit:
I wanted to post this as a comment, but I is too long. I needed a dynamic redirect for one of my apps, and used the following solution (it uses the controller that called it instead of the static URL in web.config). When testing this with your example, it fixes the issue. But I can not figure out why. Maybe it will lead you to the right path or someone else can clarify.
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1.App_Start
{
public class LoginRequiredAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "controller", filterContext.RouteData.Values[ "controller" ] },
{ "action", "Login" },
{ "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
});
}
}
}
}
Then just change the action to use the new attribute:
[LoginRequired]
public ActionResult TestMe()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With