簡體   English   中英

如何“克隆”傳入的ASP.NET MVC Multipart請求以發送到Web API控制器

[英]How to 'clone' an incoming ASP.NET MVC Multipart request to send to a Web API controller

在不執行Server.TransferRequest的情況下,我需要一種將ASP.NET MVC控制器請求的多部分主體發送到解析該多部分數據的ASP.NET Web API控制器的方法。 我想對API進行HttpClient PostAsync傳遞,並傳遞多部分表單數據。

簡而言之,API控制器的目的是處理通用模型並將其序列化為鍵/值對。 我想使用MVC控制器來驗證各種模型,然后再將請求發送到本地API控制器。 我不想直接從表單中調用API。

步驟如下:

  1. 用戶將數據輸入頁面上的表單中(/ Home / Index)
  2. 索引控制器驗證傳入的模型。
  3. 如果有效,則索引控制器執行HttpClient POST到/ api / Forms / Submit
  4. API控制器接受多部分數據並將其轉換為鍵值對,並將數據存儲在DB中。
  5. API控制器返回帶有響應模型的HttpResponseMessage。

我無法像在API控制器上那樣讀取MVC控制器上的Request.Content對象。 “重新創建”多部分請求的最佳方法是什么?

在驗證模型后,在您的MVC控制器操作中,您可以訪問原始的基礎請求流,然后將流直接傳遞到HttpWebRequest中,如下所示:

[HttpPost]
public ActionResult Index(MyModel m)
{
    Request.InputStream.Position = 0;

    //the incoming request stream
    var requestStream = HttpContext.Request.InputStream;

    //the outgoing web request
    var webRequest = (HttpWebRequest)WebRequest.Create("http://yaddayadda/api/TargetApiController/Target");

    Stream webStream = null;

    try
    {
        //copy incoming request body to outgoing request
        if (requestStream != null && requestStream.Length > 0)
        {
            webRequest.Method = "POST";
            webRequest.ContentLength = requestStream.Length;
            webRequest.ContentType = HttpContext.Request.ContentType; // <- included for multipart form content
            webStream = webRequest.GetRequestStream();
            requestStream.CopyTo(webStream);
            webStream.Close();
        }
    }
    finally
    {
        if (null != webStream)
        {
            webStream.Flush();
            webStream.Close();    // might need additional exception handling here
        }
    }

    using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
    {
        var result = response.StatusCode;
    }


    return View();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM