我试图将一个模型发布到我的MongoDB,但Blazor应用程序的Post命令甚至没有到达控制器中API的Post方法.我已经看到了一些关于这个问题的话题,也try 了几个小时来调试这个问题.

我想发布一个非常简单的模型.

public string MomentCategoryName { get; set; }

单击按钮可激活此方法.(我为这一个硬编码了一个CategoryName.)

public async Task PostAsync(MomentCategoryModel momentCategory)
        {
            using (HttpResponseMessage response = await _api.ApiClient.PostAsJsonAsync("api/MomentCategory/Create", momentCategory))
            {
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception();
                }
            }
        }

baseuri和客户机在另一个类中初始化,但整个uri如下所示:https://localhost:7141/api/MomentCategory/Create

MomentCategoryController中的PostMomentCategory从另一个库中获得MomentCategoryModel:

[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string Id { get; set; }
public string MomentCategoryName { get; set; }

然后在这个过程中,这个代码应该运行,但编译器永远不会得到这个结果,它永远不会运行:

[HttpPost]
[Route("Create")]
public void PostMomentCategory(MomentCategoryModel model)
{
    _momentCategoryData.CreateMomentCategory(model);
}

正因为如此,我收到了一个不好的请求.但当我执行一个几乎相同的GET请求时,它会正确运行.例子:

public async Task<List<MomentCategoryModel>> GetAllAsync()
        {
            using (HttpResponseMessage response = await _api.ApiClient.GetAsync("api/MomentCategory/GetAll"))
            {
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadFromJsonAsync<List<MomentCategoryModel>>();
                    return result;
                }
                else
                {
                    throw new Exception();
                }
            }
        }

感谢您的帮助和提前抽出的时间!

推荐答案

MomentCategoryController年,我调整了Post方法如下:

[HttpPost]
[Route("Create")]
[Consumes("application/x-www-form-urlencoded")]
public void PostMomentCategory([FromForm] TestMCategoryModel model)
{
    _momentCategoryData.CreateMomentCategory(model);
}

public async Task PostAsync(MomentCategoryModel momentCategory)方法中,我添加了一个包含一个元素的KeyValuePair列表.还添加了一个HttpContent,如下所示:HttpContent httpcontet = new FormUrlEncodedContent();

通过这种方式,我得到了一个OK代码(状态代码200).如果我调整API应该使用的内容,它可能会与建议的字符串内容一起工作.我也会用它做一个测试,但现在它是这样工作的.

我要感谢每一位花时间通读这个问题并提出可能的解决方案的人!

.net相关问答推荐

如何运行大量阻塞/同步 I/O 操作

Msbuild try 构建 msbuild.exe 而不是我的 .csproj 文件

EGC / 文本元素上的 .NET String.Split

是否存在指定的(子)索引分隔符?

为什么(真的吗?)List 实现所有这些接口,而不仅仅是 IList

使用 IIS Express 托管网站(临时)

HttpClient 和使用代理 - 不断得到 407

什么是编组?当某些东西被编组时会发生什么?

你如何调试 MVC 4 API 路由?

如何让 .NET 的 Path.Combine 将正斜杠转换为反斜杠?

什么是 SUT,它来自哪里?

使用 XmlDocument 读取 XML 属性

如何在 RabbitMQ 中设置重试次数?

CryptographicException 未处理:系统找不到指定的文件

CI服务器的比较?

找不到库 hostpolicy.dll

C# ListView 列宽自动

如何为我的 C# 应用程序创建产品密钥?

名称 <...> 不存在于命名空间 clr-namespace <...>

如何将我的应用程序窗口置于最前面?