c# - 从 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)
{...}
你会碰巧看到代码有什么问题吗?
解决方案
您在 PostAsync 方法中传递了一个StringContent对象,但在您的操作中,您将模型作为参数。你有两个选择:
- 将您的操作参数更改为StringContent。
- 将 Json 解析为您的模型以将其传递给 PostAsync 方法的内容参数。
问候,
推荐阅读
- python - 如何从索引中的时间戳获取一天的秒数?
- javascript - 如何将 MongoDB ObjectID 作为十六进制字符串获取到渲染器中
- javascript - formControl 的值未显示在视图中
- scala - 如何为每个对应的唯一列值分配唯一 ID?
- java - 405 Method Not Allowed with first rest API in legacy application
- python - 将熊猫图中的 xtick 标签更改为不同的日期格式
- r - 如何在R中溶解折线
- docker - /usr/bin/env: 'node\r': 没有这样的文件或目录
- angular - Angular 5 中的 sass-loader 和 bootstrap 问题
- php - Eloquent 模型作为建造者回归