I have a Blazor WASM app and am just modifying the template weatherforecastcontroller to add a Get where I can pass in an id:
[HttpGet("{userId}")]
public string Get(string userId)
{
return userId;
}
and on component that calls it:
protected override async Task OnInitializedAsync()
{
var id = await Http.GetFromJsonAsync<WeatherForecast>("WeatherForecast/1);
}
but an error is thrown:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'.
System.NotSupportedException: The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'.
at System.Net.Http.Json.HttpContentJsonExtensions.ValidateContent (System.Net.Http.HttpContent content) <0x2f6ff90 + 0x0009a> in <filename unknown>:0
so what is wrong? If I manually type into address bar :
http://localhost:59728/weatherforecast/1
...I get the id like I expect.
This:
Http.GetFromJsonAsync<WeatherForecast>
Should be
Http.GetFromJsonAsync<string>
In other words, the type specifier, which instruct the json serializer as to what type to expect from the HTTP call is string, and not the name of a class, WeatherForecast
Update:
@page "/"
@inject HttpClient Http
<h1>@output</h1>
@code
{
private string output;
protected override async Task OnInitializedAsync()
{
var val = "1";
output = await Http.GetFromJsonAsync<string>($"WeatherForecast?value={val}");
}
}
[HttpGet]
public string Get(string value)
{
return value;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(options =>
{
options.OutputFormatters.RemoveType<StringOutputFormatter>();
});
services.AddRazorPages();
}
Note: You can also add the Produces
attribute to specify the response type format, like this:
[HttpGet]
[Produces("application/json")]
public string Get(string value)
{
return value;
}
You should also change
services.AddControllersWithViews(options =>
{
options.OutputFormatters.RemoveType<StringOutputFormatter>();
});
To
services.AddControllersWithViews();