asp.net-mvc - Blazor HttpClient 3.2.0 Get 调用抛出异常,因为响应 header 内容类型与 GetFromJsonAsync 不兼容

标签 asp.net-mvc asp.net-core blazor dotnet-httpclient blazor-server-side

我正在从 blazor 3.2.0 客户端调用 webapi:

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

抛出异常,因为 GetFromJsonAsync 需要 application/json 的内容类型 header 作为响应。

这是 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 应返回 json 格式的对象。但检查响应头类型它仍然显示 text/html。我的印象是从 IActionResult OK(..) 返回一个 json 格式的对象

enter image description here

以下是异常详细信息:

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

和启动类

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}")]

关于asp.net-mvc - Blazor HttpClient 3.2.0 Get 调用抛出异常,因为响应 header 内容类型与 GetFromJsonAsync 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62235662/

相关文章:

blazor - 单个 Blazor 项目是否可以同时包含 WebAssembly 部分和服务器端部分?

c# - WebAPI 帮助页面 - 返回或参数模型/类属性的文档

https - 设置 Identity Server 4 反向代理

c# - 如何从 blazor 中的子项调用父 razor 组件中的函数?

c# - 如何在 Identity ASP.NET Core 2.1(Identity Scaffolded)中播种用户角色

c# - 将 DbContext 添加到所有类,而不仅仅是 .NET Core 中的 Controller

c# - .NET 6 Blazor 服务器 API 调用 - 将嵌套 JSON 对象反序列化为 C# 对象

asp.net-mvc - Controller 类中授权角色的继承

asp.net-mvc - 如何在MVC3中为多行文本框创建多个编辑器模板?

c# - 用于删除 ID 不等于 ID 列表的所有对象的 LINQ 查询现在可以正常工作