Home > OS >  Why doesn't this Blazor WebAssembly api Get function work?
Why doesn't this Blazor WebAssembly api Get function work?

Time:01-21

enter image description hereI have a Blazor WASM app and am just modifying the template weatherforecastcontroller to add a Get where I can pass in an id:

        [HttpGet("{userId}")]

        public string Get(string userId)
        {
            return userId;
        }

and on component that calls it:

    protected override async Task OnInitializedAsync()
    {   
            var id = await Http.GetFromJsonAsync<WeatherForecast>("WeatherForecast/1);        
    }

but an error is thrown:

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) <0x2f6ff90   0x0009a> in <filename unknown>:0 

so what is wrong? If I manually type into address bar :

http://localhost:59728/weatherforecast/1

...I get the id like I expect.

CodePudding user response:

This:

Http.GetFromJsonAsync<WeatherForecast>

Should be Http.GetFromJsonAsync<string>

In other words, the type specifier, which instruct the json serializer as to what type to expect from the HTTP call is string, and not the name of a class, WeatherForecast

Update:

@page "/"
@inject HttpClient Http


<h1>@output</h1>

@code
{
    private string output;

    protected override async Task OnInitializedAsync()
    {
        var val = "1";
        output = await Http.GetFromJsonAsync<string>($"WeatherForecast?value={val}");

    }
}

WeatherForecastController.cs

[HttpGet]
        public string Get(string value)
        {

            return value;
        }

Startup.ConfigureServices method

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllersWithViews(options =>
            {
               options.OutputFormatters.RemoveType<StringOutputFormatter>();
            });
            services.AddRazorPages();
        }

Note: You can also add the Produces attribute to specify the response type format, like this:

    [HttpGet]
    [Produces("application/json")]
    public string Get(string value)
    {

        return value;
    }

You should also change

services.AddControllersWithViews(options =>
                {
                   options.OutputFormatters.RemoveType<StringOutputFormatter>();
                });

To

services.AddControllersWithViews();

CodePudding user response:

You say when you call the API directly, it works, but is it returning 1 or "1"? This is important as only the latter is valid JSON. Since you're asking for JSON (GetFromJsonAsync), then the raw value 1 will cause a problem. As enter image description here

Similarly, if you had tested with the endpoints returning WeatherForecast, then the Content-Type would've been application/json and your Blazor code would work. You should be able to try GetJson() in your controller and see your code work.

  •  Tags:  
  • Related