![](/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.