问题
My controller's methods in Blazor's server side WebApi returns an html/text response instead of application/json which leds to
The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'.
error. What is the best way to manually set the content type of the response to application/json?
My Controller with a Get method
[Route("api/[controller]")]
[ApiController]
public class DeveloperController : ControllerBase
{
private readonly ApplicationDBContext _context;
public DeveloperController(ApplicationDBContext context)
{
_context = context;
}
[HttpGet]
public async Task<ActionResult> Get()
{
var devs = await _context.Developers.ToListAsync();
return Ok(devs);
}
and the call from Client side page
developers = await client.GetFromJsonAsync<Developer[]>("api/developer");
Thanks for all the answers, and as always, happy coding!
EDIT1: A chrome dev console screen
回答1:
When you create a Blazor Webassembly app with the Hosted option you create an API server that also launches the SPA application.
When you call the API from the SPA, any error in routing does not give a 404 error but instead it returns a Blazor page (with "sorry, nothing here"), code 200. Because all 'remaining' urls are routed to the client.
That HTML page trips up the Json deserializer in GetFromJsonAsync(). Resulting in the errormessage:
The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'
So, in conclusion, your API method is fine. It just never is called. Put a breakpoint in the Get() action, it won't be hit. You have to debug the routing (server) and url (client) combination.
In this case, the error is not in the posted code, that should have worked. It must be a change you made in index.cshtml , Server.Startup.cs or Client.Program.cs
来源:https://stackoverflow.com/questions/63861247/blazors-webapi-returns-text-html-instead-of-application-json