sukesh
sukesh

Reputation: 2437

How to redirect with Status Code to another URL in MVC Controller

I would like to redirect the user to another URL but along with a status code.

The following code does the redirection, but the Status code is always 302.

public ActionResult RedirectWithStatusCode(string redirectionUrl, int statusCode)
{
     try
     {
           Response.StatusCode = statusCode;
           return Redirect(redirectionUrl);
     }
     catch (Exception ex)
     {
           Response.StatusCode = 404;
           //log exception
           return new EmptyResult();
     }            
}

Upvotes: 1

Views: 1809

Answers (1)

Bruno Farias
Bruno Farias

Reputation: 913

Use RedirectPermanent() for Status code 301 and Redirect() for Status code 302.

There are variants like RedirectToAction(), RedirectToActionPermanent(), RedirectToRoute() and RedirectToRoutePermanent() that follows the same principle.

EDIT:

Answering your question, if you want to manipulate the response in a lower level, try the below:

public void RedirectWithStatusCode(string redirectionUrl, int statusCode)
{
    try
    {
        Response.StatusCode = statusCode;
        Response.Headers["Location"] = redirectionUrl;
        Response.End();
    }
    catch (Exception ex)
    {
        Response.StatusCode = 404;
        //log exception
        Response.End();
    }
}

Test URL: /redirectwithstatuscode?statuscode=308&redirectionurl=http://google.com

enter image description here

Warning: You may need to make sure the URL passed belongs to your domain, otherwise you may expose your website to redirection attacks.

Upvotes: 1

Related Questions