Blazor的WebApi返回text/html而不是application/json [英] Blazor's WebApi returns text/html instead of application/json

查看:49
本文介绍了Blazor的WebApi返回text/html而不是application/json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器在Blazor的服务器端WebApi中的方法返回html/text响应而不是application/json,这导致不支持提供的ContentType.支持的类型为'application/json'和结构化语法后缀'application/+ json'.错误.手动将响应的内容类型设置为application/json的最佳方法是什么?

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?

带有Get方法的我的控制器

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!

Chrome开发者控制台屏幕

A chrome dev console screen

推荐答案

使用托管"选项创建Blazor Webassembly应用程序时,会创建一个API服务器,该服务器还将启动SPA应用程序.

When you create a Blazor Webassembly app with the Hosted option you create an API server that also launches the SPA application.

当您从SPA调用API时,路由中的任何错误均不会给出404错误,而是返回Blazor页面(带有抱歉,这里没有内容"),代码200.因为所有剩余" URL都被路由到客户端.

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.

该HTML页面触发了GetFromJsonAsync()中的Json解串器.导致错误消息:

That HTML page trips up the Json deserializer in GetFromJsonAsync(). Resulting in the errormessage:

不支持提供的ContentType;支持的类型为"application/json",结构化后缀为"application/+ json"

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

因此,总而言之,您的API方法很好.只是从来没有被调用.在Get()操作中放置一个断点,它将不会被击中.您必须调试路由(服务器)和url(客户端)组合.

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.

在这种情况下,该错误不在发布的代码中,应该已经解决了.它必须是您在index.cshtml,Server.Startup.cs或Client.Program.cs

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

这篇关于Blazor的WebApi返回text/html而不是application/json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆