Send Http Request from Blazor Component

Viewed 1079

I'm using .Net Core 3.1 and I'm having trouble sending requests from a Blazor component. I want to send a request to a controller I have, and these requests systematically end up in 400 Bad request.

In my Startup.cs, I have

            if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
            {
                services.AddScoped<HttpClient>(s =>
                {
                    var uriHelper = s.GetRequiredService<NavigationManager>();
                    return new HttpClient
                    { 
                        BaseAddress = new Uri(uriHelper.BaseUri)
                    };
                });
            }

In my Blazor component, I have:

        var json2 = Newtonsoft.Json.JsonConvert.SerializeObject(_Model);
        var stringContent2 = new StringContent(json2, System.Text.Encoding.UTF8, "application/json");

        var response2 = await Http.PostAsync("/[controllerName]/[Method]", stringContent2);

        if (response2.IsSuccessStatusCode)
        {
            var resultContent = response2.Content.ReadAsStringAsync().Result;
            return resultContent;
        }
        else
            return "failed";

And here is my Controller Method prototype:

        [HttpPost] 
        public IActionResult Method([FromBody] Model form)
        {...}

Would you happen to see what's wrong with the code?

2 Answers

You are passing a StringContent object in your PostAsync method, but in your action you have your Model as a parameter. You have two options :

  1. To change your action parameter to a StringContent.
  2. To parse the Json as your Model to pass it to the PostAsync method content parameter.

Regards,

these requests systematically end up in 400 Bad request.

Please check you provide correct request header(s) and well-formatted data while you make request from your Blazor app to backend service.

I did a test using following code snippet with simple testing data, which work well on my side. If possible, you can create a new component and test if the code snippet can work for you.

var _Model = new Model { Id = 1, Name = "fehan" };

var json2 = Newtonsoft.Json.JsonConvert.SerializeObject(_Model);
var stringContent2 = new StringContent(json2, System.Text.Encoding.UTF8, "application/json");

var response2 = await Http.PostAsync("Home/Method", stringContent2);

if (response2.IsSuccessStatusCode)
{
    var resultContent = response2.Content.ReadAsStringAsync().Result;
}

Model class

public class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Test Result

enter image description here

Besides, if you are making request to MVC controller action, please check if you enabled antiforgery validation on controller or action(s).

Related