繁体   English   中英

Angular/C# null 正文已发送以进行 POST

[英]Angular/C# null body sent for POST

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

我在 Angular 中有以下代码:

项目服务.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,
            ...
        };
    }
}

我的后端/POST 代码在 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中的 int 变量在前端被认为是一个可选的 int/number,但在后端, ItemBody没有反映这一点,并且被认为只是一个int而不是int? . 我不得不通过调试器挖掘我的ModelState错误,它暗示了这一点,但是已经很晚了,我的大脑没有处理它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM