2010-01-20 99 views
1

如何將操作結果的結果設置爲使用Post和Not Get。 我需要將結果重定向到需要使用post方法發送數據的外部站點。Asp.Net MVC後操作結果

(想知道如何使用httpverbs.post過濾器重定向到另一個動作 - 但在這一點上對我而言並不重要)。

回答

3

根據定義,重定向會生成一個GET請求。您可以使用WebClient代表他們進行POST,但您無法使用POST重定向他們的瀏覽器。如果帖子需要轉到另一個站點,您可能只需簡單地生成表單操作,以便直接發佈。

+0

謝謝!我將創建一個隱藏所有字段的視圖,並使用js單擊提交按鈕。 – Debra 2010-01-21 07:08:52

0

您可以執行以下操作:返回一個操作結果,該結果發出一個帶有字段的表單並使用一些JavaScript自動發佈發出的表單。

這裏是代碼HttpPostResult

public class HttpPostResult : 
    ActionResult 
{ 

    string _formName; 
    NameValueCollection _inputs; 
    string _url; 

    public HttpPostResult(
     string url , 
     NameValueCollection inputs , 
     string formName = "form1") 
    { 
     _url = url; 
     _inputs = inputs; 
     _formName = formName; 
    } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     // Html generation 
     var html = new StringBuilder(); 
     html.Append("<html><body onload=\"document.form1.submit()\">"); 
     html.AppendFormat(
      "<form name=\"{0}\" method=\"POST\" action=\"{1}\">" , 
      _formName , 
      _url 
      ); 
     foreach(var key in _inputs.AllKeys) 
      html.AppendFormat(
       "<input name=\"{0}\" type=\"hidden\" value=\"{1}\">" , 
       key , 
       _inputs[ key ] 
       ); 
     html.Append("</form></body></html>"); 

     // Write to Response stream 
     context.HttpContext.Response.Write(html.ToString()); 
     context.HttpContext.Response.End(); 
    } 

} 

然後,當你需要在你的控制器動作結果返回一個POST而不是GET使用:

return new HttpPostResult(url , inputs);