Blazor HttpClient 3.2.0 获取调用抛出异常,因为响应 header content-type 与 GetFromJsonAsync 不兼容

Blazor HttpClient 3.2.0 Get call throwing exception because response header content-type not compatible with GetFromJsonAsync

我正在从 blazor 3.2.0 客户端调用网络api:

 protected override async Task OnParametersSetAsync()
{
    if (SelectedComplexId != Guid.Empty)
    {
        residents = await HttpClient.GetFromJsonAsync<List<ResidentDTO>>($"api/complex/residents/{SelectedComplexId.ToString()}");
    }
}

正在抛出异常,因为 GetFromJsonAsync 需要 content-type header 的 application/json 作为响应。

这是api操作方法:

[HttpGet("/residents/{complexId}")]
    public async Task<IActionResult> GetResidents([FromBody] string complexId)
    {
        var complexclaim = new Claim("complex", complexId);
        var complexUsers = await userManager.GetUsersForClaimAsync(complexclaim);
        var residents = mapper.Map<List<ResidentDTO>>(complexUsers);
        return Ok(residents);
    }

这个api应该return一个json格式化object。但是检查响应 header 类型仍然显示 text/html。我的印象是 json 格式的 object 是 return 从 IActionResult OK(..)

编辑的

以下是异常详情:

Unhandled exception rendering component: The provided ContentType is not supported; the supported types are 'application/json' and the structured syntax suffix 'application/+json'.

和启动 class

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoMapper(typeof(Startup));

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

        services.AddAuthentication()
            .AddIdentityServerJwt();

        services.AddControllersWithViews()
            .AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

        services.AddRazorPages();
        services.Configure<EmailOptions>(Configuration.GetSection("EmailSettings"));
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddTransient<IMailJetEmailService, MailJetEmailService>();
        services.AddTransient<IManagingAgentService, ManagingAgentService>();
        services.AddTransient<IProfileService, ProfileService>();

    }


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseWebAssemblyDebugging();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseBlazorFrameworkFiles();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseIdentityServer();
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllers();
            endpoints.MapFallbackToFile("index.html");
        });
    }

我认为您返回的 HTML 页面有错误。调试您的 API 操作或深入了解响应的内容。它可能来自 app.UseDeveloperExceptionPage();

该错误很可能是由于路由或授权方面的问题造成的。
运行 Kestrel 控制台打开可能还会提供更多信息。


你可以替换

[HttpGet("/residents/{complexId}")]

[HttpGet("/api/residents/{complexId}")]

好的 - 问题是路由 - [HttpGet("/residents/{complexId}")] 应该是 [HttpGet("residents/{complexId}")].

控制器有路由属性:[Route("api/[controller]")] ...所以你会认为你需要一个“/”但显然不需要。