Now with .NET Core 3, Microsoft released a new .NET Core HTTP client.
Reference: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1
With the new client, to call a WEB API is much easier.
For example, to make an HTTP GET request:
var client = new HttpClinet();
var request = new HttpRequestMessage(HttpMethod.Get, url)
{
Content = new FormUrlEncodedContent(new Dictionary<string, string>())
};
request.Headers.Add("accept", "application/json");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
throw new WebException($"The remote server returned unexpcted status code: {response.StatusCode} - {response.ReasonPhrase}.");
}
Typically, when we call a Web API, we don't need to submit a binary file with it. But with the new client, how can we submit files to the server?
As you can see, an HTTP POST request with a file is different from form URL encoded content. The form was divided by some boundaries. And the name of the boundary was specified in the HTTP header: content type.
To submit a file from .NET Core HTTP client, use MultipartFormDataContent
so the framework can handle the multipart content.
var formData = new MultipartFormDataContent();
To add your file to it, simply add a new stream content.
formData.Add(new StreamContent(fileStream), name: "file", fileName: "file");
Also, you can add other content like URL encoded content to it.
And finally, submit it.
var formData = new MultipartFormDataContent();
formData.Add(new StreamContent(fileStream), "file", "file");
var request = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = formData
};
request.Headers.Add("accept", "application/json");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
throw new WebException($"The remote server returned unexpcted status code: {response.StatusCode} - {response.ReasonPhrase}.");
}
And your file is uploaded to the server.
I believe the most common scenario would be to upload the file along with some normal textual data, i.e. post user id, along with its avatar file content, in one single network request, so that the api can associate the avatar to the right user. Is this possible?