1
        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.

Ameya
  • 504
  • 3
  • 12
apc
  • 5,306
  • 1
  • 17
  • 26
  • try something like this : private static async Task PostJsonHttpClient(string uri, HttpClient httpClient) { var postUser = new User { Name = "Steve Gordon" }; var postResponse = await httpClient.PostAsJsonAsync(uri, postUser); postResponse.EnsureSuccessStatusCode(); } – etaskin Jul 15 '22 at 12:59
  • Does this answer your question? [c# HttpClient post response content-type application/json](https://stackoverflow.com/questions/63068504/c-sharp-httpclient-post-response-content-type-application-json) – gunr2171 Jul 15 '22 at 13:00
  • @etaskin unfortunatly I cant use PostAsJsonAsync as I need set NoCors – apc Jul 15 '22 at 13:00
  • @mason Content-Type can't be set on the request, it has to be set on the content otherwise you get an exception of "Misused header name, 'Content-Type'." – apc Jul 15 '22 at 13:02
  • 1
    @gunr2171 No luck, tried that. I'm beginning to think this is a bug in Blazor WebAssembly – apc Jul 15 '22 at 13:04
  • Have you tried `content.Headers.ContentType = MediaTypeHeaderValue("application/json")`? – silkfire Jul 15 '22 at 13:24
  • @silkfire just tried but no effect, its actually already set to the correct value. – apc Jul 15 '22 at 13:27
  • 1
    Running the same code in a .NET6 Console application works suggesting this is a bug with ASP Core / Blazor Web Assembly – apc Jul 15 '22 at 13:44
  • I'm having a hard time reproducing your issue, even in .Net 6 Blazor Web Assembly. https://gist.github.com/gunr2171/d8bd54b249e9fd7ea07dccdc8fe1930e – gunr2171 Jul 15 '22 at 15:12
  • @gunr2171 something to do with nocors perhaps? Similar issue here but not .net https://github.com/aurelia/http-client/issues/186 – apc Jul 16 '22 at 18:18
  • It looks like when using nocors the only allowed content types are "application/x-www-form-urlencoded", "multipart/form-data", or "text/plain" – apc Jul 16 '22 at 18:26
  • See the fetch specification which I would think the Web Assembly HttpClient uses https://fetch.spec.whatwg.org/#terminology-headers – apc Jul 16 '22 at 18:52
  • There's no such content type bug. If there was, *No Blazor Webassembly* application would work. Even the `FetchData` page in the project template would fail. – Panagiotis Kanavos Jul 18 '22 at 16:48
  • 2
    Why are you trying to disable CORS instead of adding the URLs you want on the server config? – Panagiotis Kanavos Jul 18 '22 at 16:53
  • I am trying to communicate from the client browser to a web service installed on the client (not the server) (this is for an industrial application not a consumer website). I'm probably misunderstanding how Blazor and CORS works but wouldn't adding the URL on the server only work for routing the requests via the server? Doesn't the config for the client need to be in the client WASM project? – apc Jul 19 '22 at 09:03
  • OK, got a bit more understanding now. Without NoCors the preflight requests are being rejected by the local service (which doesn't support them). While not being able to send the correct content type with NoCors on I have found a way to configure the local service to default to JSON which solves my issue though not the original issue. – apc Jul 19 '22 at 09:21

2 Answers2

0

I think you could check these case: case1,case2 read this document,and try with PostAsJsonAsync method

I tested as below and worked well:

var weatherforecast = new WeatherForecast() { Date = DateTime.Now, Summary = "testsummary", TemperatureC = 44 };           
var response = await Http.PostAsJsonAsync("https://localhost:44385/WeatherForecast", weatherforecast);

Result: enter image description here

Ruikai Feng
  • 6,823
  • 1
  • 2
  • 11
0

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)

apc
  • 5,306
  • 1
  • 17
  • 26