.Net - Use HttpClient to POST a file?

2020-07-10 11:26发布

I have a debug method that I'm trying to use to use to post multiple files to a local endpoint to simulate a series of uploads.

I have the following code:

var fi = new FIleInfo(....);
var form = new MultipartFormDataContent();
form.Add(new StreamContent(fi.OpenRead()), "file", fi.Name);
client.PostAsync(@"http://localhost:12372/TemplateManagement/Asset/Create", form);

that I want to post to a method with the following signature (asset comes from a custom binder but that's not important):

public JsonResult Create(HttpPostedFileBase file, DynamicBuilderAsset asset)

The post gets made ok but the file parameter is null. What am I missing here?

1条回答
我想做一个坏孩纸
2楼-- · 2020-07-10 12:08

Try quoting the name and the filename:

form.Add(new StreamContent(fi.OpenRead()), "\"file\"", "\"" + fi.Name + "\"");

And the same is true if you are sending standard keys:

form.Add(new StringContent("some asset data"), "\"asset\"");
查看更多
登录 后发表回答