Removing the Object Moved HTML in the body on a Response.Redirect

.net, asp.net, asp.net-mvc, c#

Solution

You can do this by implementing your own `ActionResult` instead of using the built in `RedirectResult`, which will send that HTML.

However, you should not need to - the user should never see that markup, but it is provided for, mostly, legacy issues. Also be aware some browsers can be set to not follow redirects - not having the body there would then render the result pretty useless.

If you still want a Redirect without body, this result class would do it:

public sealed class RedirectResultNoBody : ActionResult
{
    private readonly string location;
    public RedirectResultNoBody(string location) 
    {
        this.location = location;
    }
    public override void ExecuteResult(ControllerContext context) 
    {
        var response = context.HttpContext.Response;
        response.StatusCode = 302;
        response.RedirectLocation = location;
        response.End();
    }
}

Which would then be used like this:

public ActionResult Redirect()
{
    return new RedirectResultNoBody("http://url.com");
}

Problem

I have a simple redirect in my code: ``` public ActionResult Redirect() { return Redirect("http://url.com"); } ``` I noticed that the response includes the following html in the response body: ``` HTTP/1.1 302 Found Cache-Control: private Content-Type: text/html; charset=utf-8 Location: http://url.com Server: Microsoft-IIS/7.0 Date: Tue, 24 Jul 2012 18:53:52 GMT Content-Length: 198 <html><head><title>Object moved</title></head><body> <h2>Object moved to <a href="http://url.com">here</a>.</h2> </body></html> ``` Is there a way to remove the html from the response body? I would like the Content-Length to be zero by not having anything in the response body.

Original source