gpt4 book ai didi

c# - ASP.NET 如何在 Web API 中读取多部分表单数据?

转载 作者:可可西里 更新时间:2023-11-01 08:18:42 24 4
gpt4 key购买 nike

我像这样将多部分表单数据发送到我的 Web API:

string example = "my string";
HttpContent stringContent = new StringContent(example);
HttpContent fileStreamContent = new StreamContent(stream);
using (var client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
content.Add(stringContent, "example", "example");
content.Add(fileStreamContent, "stream", "stream");
var uri = "http://localhost:58690/api/method";
HttpResponseMessage response = await client.PostAsync(uri, content);

这是 Web API:

[HttpPost]
[Route("api/method")]
public async Task<HttpResponseMessage> Method()
{
// take contents and do something
}

如何从我的 Web API 中的请求主体读取字符串和流?

最佳答案

这应该可以帮助您入门:

 var uploadPath = HostingEnvironment.MapPath("/") + @"/Uploads";
Directory.CreateDirectory(uploadPath);
var provider = new MultipartFormDataStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(provider);

// Files
//
foreach (MultipartFileData file in provider.FileData)
{
Debug.WriteLine(file.Headers.ContentDisposition.FileName);
Debug.WriteLine("File path: " + file.LocalFileName);
}

// Form data
//
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Debug.WriteLine(string.Format("{0}: {1}", key, val));
}
}

关于c# - ASP.NET 如何在 Web API 中读取多部分表单数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40632028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com