c# setting uploadFile content-Type

2019-04-10 18:05发布

I am trying to create an api call to my server that will allow me to upload a .csv file.

client side code

string url = "http://testserver/testapi";
string filePath = @"C:\test.csv";
using (WebClient wc = new WebClient())
{
    wc.Headers.Add("Content-Type", "text/plain");
    byte[] responseArray = wc.UploadFile(url, filePath);
}

server side code

string savePath = testSavePath;
foreach (string f in Request.Files.AllKeys)
{
    HttpPostedFileBase file = Request.Files[f];
    file.SaveAs(savePath);
}

I am getting an exception on this line byte[] responseArray = wc.UploadFile(url, filePath);

The strange thing is that when I look at Request I see

ContentType="multipart/form-data; boundary=---------------------8d006b7c2a5452c".

Looking at the docs for UploadFile I see that a WebException will be thrown when The Content-type header begins with multipart.

My question is why is contentType getting set to multipart and how do I prevent it from doing so?

1条回答
Explosion°爆炸
2楼-- · 2019-04-10 18:28

Your client code seems ok. The exception may be coming from the server-side. But that's hard to judge as you did not share the exception. Please do, you will get better answers.

For the multipart content type: The WebClient.UploadFile uses value of Content-Type header for content type of the file (defaulting to application/octet-stream if not set), not a whole HTTP request. The actual HTTP request is always (as you have found) multipart/form-data (as per HTTP specification for uploading files) and you cannot (and should not) change it. The note in documentation refers to content type of the actual file. It means that you cannot ask WebClient to upload file that is multipart on its own (that would be wrapped in another multipart HTTP envelope).

查看更多
登录 后发表回答