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

和自甴很熟 提交于 2020-07-22 06:08:36

问题


I am calling a webapi from a blazor 3.2.0 client:

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

An exception is being thrown because the GetFromJsonAsync expects a content-type header of application/json in response.

This is the api action method:

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

This api should return a json formatted object. But inspecting the response header type its still showing text/html. I was under the impression that a json formatted object is returned from IActionResult OK(..)

Here are exception details:

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

And Startup 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");
        });
    }

回答1:


I think you are getting an error back as an HTML page. Debug your API Action or take a deeper look in the content of the response. It probably comes from app.UseDeveloperExceptionPage();

The error is most likely from some problem with Routing or Authorization.
Running with the Kestrel console open might also give more information.


You can replace

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

with

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



回答2:


OK - the issue was the routing - [HttpGet("/residents/{complexId}")] should have been [HttpGet("residents/{complexId}")].

The controller has the route attribute : [Route("api/[controller]")] ... so you would think you need a "/" but apparently not.



来源:https://stackoverflow.com/questions/62235662/blazor-httpclient-3-2-0-get-call-throwing-exception-because-response-header-cont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!