9

Does anyone know how to redirect current request in ASP.NET using http status code 303 (SeeOther).

Code snippets are more than welcome!

ono2012
  • 4,967
  • 2
  • 33
  • 42
ni5ni6
  • 453
  • 6
  • 13

2 Answers2

16

You should be able to do it like this:

  HttpContext.Current.Response.Clear();
  HttpContext.Current.Response.Status = "303 See Other";
  HttpContext.Current.Response.AddHeader("Location", newLocation);
  HttpContext.Current.Response.End();
Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
8

This is a .NetCore / .Net5.0+ implementation as an extension method.

public static class ControllerExtensions
{
    public static ActionResult SeeOther(this Controller controller, string location)
    {
        controller.Response.Headers.Add("Location", location);
        return new StatusCodeResult(303);
    }
}

Usage From Controller: return this.SeeOther("/resource-endpoint");

N-ate
  • 6,051
  • 2
  • 40
  • 48
  • HTTP 303 is for "See Other", not for "Exists". There is no HTTP status code named "Exists". – Dai May 03 '21 at 22:13
  • Consider using `this ControllerBase` instead, and `Uri location` for strong-typing, and to signal intent (a `Uri` object can be used to represent a relative URI, not just absolute URIs) – Dai May 03 '21 at 22:14
  • I admit my second comment was nit-picking, certainly - but my first comment is serious. HTTP 303 is well-defined as “See Other” (read the spec!). The semantics of HTTP 303 do not say nor suggest the `Location:` destination “exists” (e.g. it’s valid for a 303 redirect to result in a 404). I’m asserting that you are flat-out incorrect by naming your method `Exists` instead of `SeeOther`. – Dai May 04 '21 at 02:01