为开机自检发送的角度/C# 空正文



我尝试在Angular中做一个POST,它会调用我的C#后端。一个 API 调用工作正常,但另一个不完全有效。我很难弄清楚发生了什么,但我看到当我在浏览器的 DevTools 中打开"网络"窗口时,请求有效负载很好地填充了 JSON。但是在 C#/后端中,它接收一个空对象,我从调用中得到一个 200 代码/空响应。

我在 Angular 中有以下代码:

item.service.ts

private readonly _api = '...'
private postOptions = { headers: { 'Content-Type': 'application/json; charset=utf-8' }};
public addItem(formGroup: formGroup, isInactive: boolean): Observable<Item> {
let api = ``;
// These require different API calls depending on the flag
if (isInactive)
api = `${this._api}/AddInactiveItem`;
else
api = `${this._api}/AddItem`; // This one is the one having issues
const body = ItemPost.parse(formGroup.value);
return this.http.post<Item>(api, body, this.postOptions).pipe(
this.handle(
"POST successful",
"Error with POST"
)
);
}

item-post.ts

export class ItemPost {
Name: string;
Inactive: string;
...
public static parse(obj: any): ItemPost {
return !obj ? undefined : {
Name: obj.name, 
Inactive: obj.inactive,
...
};
}
}

我的后端/开机自检代码是 C# 格式的。我的两个 POST 方法构建完全相同,但具有不同的 SQL 调用。

[HttpPost]
public JsonResult AddInactiveItem([FromBody] ItemBody item)
{
if (!ModelState.IsValid)
return Json(null);
// Do SQL call for POST here, return JSON
}
[HttpPost]
public JsonResult AddItem([FromBody] ItemBody item) // This is where I have a breakpoint and it's passing in null
{
if (!ModelState.IsValid)
return Json(null);  // And this is where I find myself
// Do SQL call for POST here, return JSON
}

JSON 有效负载(抱歉,无法获取屏幕截图,但这就是我所看到的(:

{"Name":"Test", ..., "Inactive":"N"}

我认为您在以下方面遇到了问题:

`$(this.api}/AddInactiveItem`

模板字符串的正确语法是:

`${this.api}/AddInactiveItem`

我想通了...我觉得自己很笨。真的很笨。

当 Item 被认为是活动(非活动(时,Item中的 int 变量在前端被认为是可选的 int/number,但在后端,ItemBody没有反映这一点,并且被视为只是一个int而不是int?。我不得不通过调试器挖掘我的ModelState错误,它暗示了这一点,但现在是深夜,我的大脑没有处理它。

必须确保所有变量类型都正确反映在 Body 对象中。

最新更新