HttpClient httpClient = new HttpClient();
MyRequest request = new MyRequest (data);
var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(request), System.Text.Encoding.UTF8, "application/json");
HttpRequestMessage httpRequestMessage = new HttpRequestMessage
{
RequestUri = new Uri("http://localhost:8000/api/action"),
Content = content,
Method = HttpMethod.Post
};
httpRequestMessage.SetBrowserRequestMode(BrowserRequestMode.NoCors);
await httpClient.SendAsync(httpRequestMessage);
Using HttpClient in Blazor WebAssembly I am trying to send a request to an API.
However, despite specifying application/json
as the content type it sends text/plain;charset=UTF-8
(as viewed in the Chrome Network tab). This results in the API throwing an error.
CodePudding user response:
I think you could check these case:
CodePudding user response:
Related post: Wrong Content-Type being substituted for fetch http request
HttpClient in WebAssembly calls the standard fetch method.
As per the fetch specification when using no-cors only a limited number of content-types can be used: https://fetch.spec.whatwg.org/#simple-header
- "application/x-www-form-urlencoded"
- "multipart/form-data"
- "text/plain"
The preferred solution would be to correctly configure the end point you are calling to allow cross origin requests and not to use no-cors e.g: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin Access-Control-Allow-Origin: *
If this is not possible (as in my case) and you must use no-cors the only other option would be to change your end point to map "text/plain" to "application/json"
Whilst many may not consider this a bug it is an inconsistency in how HttpClient behaves and is not obvious (though the NoCors option is only available in WebAssembly)