[英]How to 'clone' an incoming ASP.NET MVC Multipart request to send to a Web API controller
Without performing a Server.TransferRequest I need a way to send the multipart body of an ASP.NET MVC Controller Request to an ASP.NET Web API controller which parses that multipart data. 在不执行Server.TransferRequest的情况下,我需要一种将ASP.NET MVC控制器请求的多部分主体发送到解析该多部分数据的ASP.NET Web API控制器的方法。 I would like to do an HttpClient PostAsync to the API passing along the multipart form data.
我想对API进行HttpClient PostAsync传递,并传递多部分表单数据。
In a nutshell, the purpose of the API controller is to handle generic models and serialize them into key/value pairs. 简而言之,API控制器的目的是处理通用模型并将其序列化为键/值对。 I want to use the MVC controllers to validate various models before sending the request on to the local API Controller.
我想使用MVC控制器来验证各种模型,然后再将请求发送到本地API控制器。 I do not want to call the API directly from the form.
我不想直接从表单中调用API。
Here are the steps: 步骤如下:
I cannot read a Request.Content object on the MVC controller like I can on the API controller. 我无法像在API控制器上那样读取MVC控制器上的Request.Content对象。 What is the best way to 're-create' the multipart request?
“重新创建”多部分请求的最佳方法是什么?
In your MVC controller action after validating the model you can access the raw underlying request stream then pass the stream directly into an HttpWebRequest like so... 在验证模型后,在您的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.