Blazor 的 WebApi returns text/html 而不是 application/json

Blazor's WebApi returns text/html instead of application/json

我的控制器在 Blazor 的服务器端 WebApi 中的方法 returns 一个 html/text 响应而不是 application/json 导致 The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'. 错误。将响应的内容类型手动设置为 application/json 的最佳方法是什么?

我的带有 Get 方法的控制器

 [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);
        
    }

以及来自客户端页面的调用

developers = await client.GetFromJsonAsync<Developer[]>("api/developer");

感谢您的所有回答,一如既往,祝您编码愉快!

EDIT1:chrome 开发控制台屏幕

当您使用托管选项创建 Blazor Webassembly 应用程序时,您会创建一个 API 服务器,该服务器也会启动 SPA 应用程序。

当您从 SPA 调用 API 时,路由中的任何错误 不会 给出 404 错误,而是 returns Blazor 页面(与“抱歉,这里什么都没有”),代码 200。因为所有 'remaining' url 都被路由到客户端。

HTML 页面使 GetFromJsonAsync() 中的 Json 反序列化器跳闸。导致错误消息:

The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'

所以,总之,您的 API 方法没问题。它只是永远不会被调用。在 Get() 操作中放置一个断点,它不会被击中。您必须调试路由(服务器)和 url(客户端)组合。

在这种情况下,错误不在发布的代码中,应该有效。它必须是您在 index.cshtml 、 Server.Startup.cs 或 Client.Program.cs

中所做的更改