ASP.Net MVC - HTTP status codes (i.e. 303, 401, 404, etc.)

In ASP.Net MVC, can you use either Redirect or RedirectToAction to call, for example, error 303?

I am working on a book called ASP.NET MVC 1.0 Website Programming, and the source makes calls such as return this.Redirect(303, FormsAuthentication.DefaultUrl); , but this call only works with an external library, I would like to have the same functionality without the possibility of adding.

+6
asp.net-mvc asp.net-mvc-routing routing
source share
4 answers

You can create custom ActionResults that mimic any HTTP response code. By returning these action results, you can easily complete 303.

I found this quick entry with which you should easily follow.

+4
source

Here's what I came up with based on the recommendations given in the current answers and decompiled System.Web.Mvc.RedirectResult code:

 public class SeeOtherRedirectResult : ActionResult { public string Url { get; private set; } public HttpStatusCode StatusCode { get; private set; } public SeeOtherRedirectResult(string url, HttpStatusCode statusCode) { if (String.IsNullOrEmpty(url)) { throw new ArgumentException("URL can't be null or empty"); } if ((int) statusCode < 300 || (int) statusCode > 399) { throw new ArgumentOutOfRangeException("statusCode", "Redirection status code must be in the 3xx range"); } Url = url; StatusCode = statusCode; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (context.IsChildAction) { throw new InvalidOperationException("Cannot redirect in child action"); } context.Controller.TempData.Keep(); context.HttpContext.Response.StatusCode = (int) StatusCode; context.HttpContext.Response.RedirectLocation = UrlHelper.GenerateContentUrl(Url, context.HttpContext); } } 
+3
source

2 ways about it -

  Response.Redirect(url, false); //status at this point is 302 Response.StatusCode = 303; 

-or -

  Response.RedirectLocation = url; Response.StatusCode = 303; 

Note that the first time you redirect, a false parameter throws a threadAbort exception, which usually redirects a URL (url). This is one good reason to use one of these two methods.

+1
source

You can also execute it using a special ActionFilter, as I mention here . I for one, like ActionFilter, have a bit more ActionResult.

0
source

All Articles