![](/img/trans.png)
[英]Which formatter is used when I send a multipart request to a Web API Controller in ASP.NET CORE?
[英]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。
步驟如下:
我無法像在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.