【问题标题】:The provided ContentType is not supported; the supported types are 'application/json' in blazor不支持提供的 ContentType;支持的类型是 blazor 中的“应用程序/json”
【发布时间】:2020-12-19 07:26:48
【问题描述】:

我在 blazor webassemblyapp(client side) 中调用 blazor serverapp(webwebapi),但遇到内容类型错误:

crit: 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) <0x32571f8 + 0x0009a> in <filename unknown>:0 
  at System.Net.Http.Json.HttpContentJsonExtensions.ReadFromJsonAsync[T] (System.Net.Http.HttpContent content, System.Text.Json.JsonSerializerOptions options, System.Threading.CancellationToken cancellationToken) <0x3256ff0 + 0x00006> in <filename unknown>:0 
  at System.Net.Http.Json.HttpClientJsonExtensions.GetFromJsonAsyncCore[T] (System.Threading.Tasks.Task`1[TResult] taskResponse, System.Text.Json.JsonSerializerOptions options, System.Threading.CancellationToken cancellationToken) <0x321fd50 + 0x0011c> in <filename unknown>:0 
  at CrudBlazorClientApp.Pages.Index.Login () [0x00106] in C:\Users\FrontTech\source\repos\CrudBlazorServerApp\CrudBlazorClientApp\Pages\Index.razor:31 
  at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion (System.Threading.Tasks.Task task) <0x3220cb0 + 0x000da> in <filename unknown>:0 
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x3156c98 + 0x000b6> in <filename unknown>:0 

EmpsController.cs

namespace CrudBlazorServerApp.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmpsController : ControllerBase
    {
        //here I create a custom login webapi 
        [HttpPost]
        [Consumes("application/json")]
        public Emp checkLogin(string username, string password)
        {
            Emp hasemp = _context.emps.Where(e => e.username == username & e.password == password).FirstOrDefault();
            return hasemp;
        }

参见上面的 webapi 响应

查看观察窗口

查看控制台日志

请求标头

回应

未能加载响应数据

Index.razor

@page "/"
@using CrudBlazorServerApp.Data
@inject HttpClient Http
@inject NavigationManager navigationManager
@*@inject CrudBlazorServerApp.Data.sqldbcontext _sqldbcontext*@
@using Newtonsoft.Json;
<div>
    UserName:<input id="txtusername" type="text" placeholder="Enter Your UserName" @bind="@username" /><br />
    Password:<input id="txtpassword" type="text" placeholder="Enter Your Password" @bind="@password" /><br />
    <button @onclick="Login">Log In</button>
</div>

@code{
    string username = "";
    string password = "";
    Emp empList = new Emp();
    protected async Task Login()
    {
        @if (username == "" || username == null && password == "" || password == null)
        {
            var data = new
            {
                message = "Enter Username ",
            };
        }
        else
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            empList = await client.GetFromJsonAsync<Emp>("https://localhost:44333/api/emps/checkLogin?username=" + empList.username + "&password=" + empList.password);

            @if (username == empList.username || password == empList.password)
            {
                var data = new
                {
                    message = "Success",
                    data = new { empList.username, empList.password }
                };

                navigationManager.NavigateTo("/registration");

            }
            else
            {
                var data = new
                {
                    message = "Username and Password incorrect ",
                };
                navigationManager.NavigateTo("/index");
            }
        }
    }
}

当我调试这一行时会产生错误:

empList = await client.GetFromJsonAsync<Emp>("https://localhost:44333/api/emps/checkLogin?username=" + empList.username + "&password=" + empList.password);

emplist 也为空

帮助

【问题讨论】:

  • 2 days ago 相同的错误,同样的问题:您的 URL 和路由不匹配。
  • @Henk Holterman 问题已解决

标签: c# blazor-server-side blazor-client-side blazor-webassembly


【解决方案1】:

我认为您需要更改此行:

empList = await client.GetFromJsonAsync&lt;Emp&gt;("https://localhost:44333/api/emps/checkLogin?username=" + empList.username + "&amp;password=" + empList.password);

empList = await client.GetFromJsonAsync&lt;Emp&gt;("https://localhost:44333/api/emps/checkLogin?username=" + username + "&amp;password=" + password);

【讨论】:

【解决方案2】:

这里似乎有几个问题。

  1. 您尝试使用的方法是 POST
[HttpPost]
[Consumes("application/json")]
public Emp checkLogin(string username, string password)

在您的客户端代码中,您正在使用

await client.GetFromJsonAsync<Emp>(".....")

该方法发出的是 GET 请求,而不是 POST 请求。在我看来,你想要的方法是PostAsJsonAsync

  1. 端点似乎不正确。在 Postman 中,您正在调用且正在使用(带有 POST 请求)的 URL 是 https://localhost:44333/api/emps?username=....,在您的 C# 代码中是 https://localhost:44333/api/emps/checkLogin?username=....

  2. (这是您的代码所抱怨的)您得到的错误是因为 HTTP 标头 Content-Type 不是 application/json。您可能需要指定此标头:

client.DefaultRequestHeaders.Add("Content-Type", "application/json");
  1. 这不会导致服务器错误,但您可能需要考虑不将凭据作为查询字符串传递,即使您的应用程序在 HTTPS 上运行。 This question 有与此主题相关的好答案。

【讨论】:

    猜你喜欢
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多