2009-12-30 106 views
6

在ASP.Net MVC中,是否可以使用RedirectRedirectToAction來調用例如303錯誤?ASP.Net MVC - HTTP狀態代碼(即303,401,404等)

我正在通過一本名爲「ASP.NET MVC 1.0網站編程」的書,源代碼正在調用如return this.Redirect(303, FormsAuthentication.DefaultUrl);這樣的調用,但這個調用只與外部庫函數有關,我希望具有相同的功能sans如果可能的話,附加組件。

回答

4

您可以創建自定義的ActionResults,以模擬任何您想要的http響應代碼。通過返回這些行動結果,您可以輕鬆地執行一個303.

我發現this quick write-up,您應該能夠輕鬆關注。

+0

太謝謝你了!我還在Phil Haack的網站上發現了這篇文章,以防將來有人發現這一點:http://haacked.com/archive/2008/12/15/redirect-routes-and-other-fun-with-routing-and -lambdas.aspx – mynameiscoffey 2009-12-30 08:13:05

+0

john-sheehan.com鏈接現在回到需要登錄的Tumblr頁面。原始可以在這裏找到:http://johnsheehan.me/blog/another-asp-net-mvc-custom-actionresult-example/ – 2012-07-04 18:35:32

+0

現在johnsheehan.me不解決,john-sheehan.com鏈接是404。編輯有archive.org頁面。這就是爲什麼提供嵌入/引用答案而不僅僅是鏈接的原因。 – gregmac 2015-04-29 19:16:58

0

你也可以使用自定義ActionFilter來完成它,比如我提到的here。我對ActionFilter更像ActionResult。

1

2板上釘釘這個 -

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

- 或 -

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

注意的是,在第一重定向,即false參數避免threadAbort異常重定向(URL)通常會拋出。這是使用這兩種方法之一的一個很好的理由。

3

這就是我想出了基於當前的答案和反編譯代碼System.Web.Mvc.RedirectResult給出的建議是:

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); 
    } 
}