简体   繁体   中英

Redirect(“/Error/UnAuthorized”) not working in ASP.NET MVC

Could anyone please help me why the following code not working? The redirect doesn't occur while debugging:

protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);

    Redirect("/Error/UnAuthorized");
}

The following should work:

protected override void Initialize(RequestContext requestContext)
{
    base.Initialize(requestContext);
    var url = Url.Action("UnAuthorized", "Error");
    requestContext.HttpContext.Response.Redirect(url);
}

This being said, you should not be doing any redirects in the Initialize method. Personally I've never had to override this method. And even worse, it seems that you are handling authorization in this method which is bad. I would strongly recommend you using a custom Authorize attribute for this purpose.

In MVC you should return a redirect result, rather than using Response.Redirect.

Also, I'd say with the error you're getting (headers sent), you're processing this too late in the request.

Here's an example of redirecting from an action method.

[HttpGet]
public ActionResult Basecamp()
{
    if (!GetPlanPolicyForUser().IntegrationEnabled)
    {
        Log<ApplicationsController>.Action( "..." );
        return Redirect("/applications/notsupported");
    }
    //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM