首页 > 解决方案 > 从 Blazor 组件发送 Http 请求

问题描述

我正在使用 .Net Core 3.1,但在从 Blazor 组件发送请求时遇到问题。我想向我拥有的控制器发送一个请求,这些请求系统地以 400 Bad request 告终。

在我的 Startup.cs 中,我有

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

在我的 Blazor 组件中,我有:

        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";

这是我的控制器方法原型:

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

你会碰巧看到代码有什么问题吗?

标签: c#asp.net-coreblazor

解决方案


您在 PostAsync 方法中传递了一个StringContent对象,但在您的操作中,您将模型作为参数。你有两个选择:

  1. 将您的操作参数更改为StringContent
  2. 将 Json 解析为您的模型以将其传递给 PostAsync 方法的内容参数。

问候,


推荐阅读