开发者

ASP.Net MVC - HTTP Status Codes (i.e. 303, 401, 404, etc)

In ASP.Net MVC is it possible to use either Redirect or RedirectToAction to call for example a 303开发者_JS百科 error?

I am working my way through a book titled "ASP.NET MVC 1.0 Website Programming" and the source is making calls such as return this.Redirect(303, FormsAuthentication.DefaultUrl); but this call only functions with an external library, I would like to have the same functionality sans the add-on if possible.


You can create custom ActionResults that mimic any http response code you'd like. By returning those action results, you can easily perform a 303.

I found this quick write-up that you should be able to follow easily.


Here's what I came up with based on the advice given in the current answers and the 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);
    }
}


2 ways about this-

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

-or-

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

Note that in the first redirect, that the false parameter avoids the threadAbort exception that the redirect(url) normally throws. This is one good reason to use one of these 2 methods.


You could also accomplish it with a custom ActionFilter like I mention here. I for one like the ActionFilter a bit more the the ActionResult.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜