C#将文件发布到WEB API [英] C# post file to WEB API
问题描述
我使用te POSTMAN应用程序将文件上传到API,
现在我想在c#中实际执行POST命令,我该如何以最有效的方式执行此操作?
url192.168.0.1/api/files
标题
key =授权,价值=123456
Formdata
key = files,value =< file>
key = Info,value =< {DocName:Test}>
如果状态== 200
控制台。 WriteLine(OK);
else
Console.WriteLine(ERROR+ response.StatusCode +:Message - + response.ReasonPhrase);
我尝试过:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(https:///api.ontriz.com/files);
client.DefaultRequestHeaders.TryAddWithoutValidation(Authorization,123456 );
然后??
I use te POSTMAN application to upload a file to an API,
now I want to actually do a POST commando in c#, how can I do this in the most efficient way?
url "192.168.0.1/api/files"
Header
key= Authorization, value = "123456"
Formdata
key= files, value = <file>
key= Info, value = <{"DocName": "Test"}>
if status == 200
Console.WriteLine("OK");
else
Console.WriteLine( "ERROR" + response.StatusCode + " : Message - " + response.ReasonPhrase);
What I have tried:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https:///api.ontriz.com/files");
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "123456");
but then??
推荐答案
使用 MultipartFormDataContent class [ ^ ] :
Use the MultipartFormDataContent class[^]:
using (var form = new MultipartFormDataContent())
using (var stream = File.OpenRead(@"Path\To\Your\File.ext"))
using (var streamContent = new StreamContent(stream))
{
form.Add(streamContent, "files");
form.Add(new StringContent("<{\"DocName\": \"Test\"}>"), "Info");
response = await client.PostAsync(null, form);
}
这篇关于C#将文件发布到WEB API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!