【问题标题】:Instant status: 400 "Bad request" upon attempting httppost即时状态:尝试 httppost 时出现 400 \"Bad request\"
【发布时间】:2022-12-14 12:10:12
【问题描述】:

我在谷歌/stackoverflow 上到处寻找我的代码可能有什么问题……但是一整天都没有结果,所以现在我转向自己写一个问题: 我的服务类中有两个几乎相同的函数,它们向我的 api/后端发出发布请求(它又包含两个几乎相同的函数来接收所述请求)。一个工作完美,另一个在生成“状态:400”之前似乎甚至没有在前端“启动”。 在我的后端/api 中:

[HttpPost("Patients/update")] //not working
        public async Task<IActionResult> UpdatePatientAsync(Patient editedPatient)
        {
            try
            {
                _logger.LogDebug("APIController.UpdatePatientAsync() was called...");
                var updated = await _dbHandler.UpdatePatientAsync(editedPatient);
                if (updated)
                {
                    return Ok(updated);
                }
                else
                {
                    return BadRequest("Patient not updated!");
                }
            }
            catch
            {
                throw;
            }

        }
[HttpPost("Patients/comment/update")] //works GREAT!
        public async Task<IActionResult> UpdatePatientCommentAsync(PatientComment editedComment)
        {
            try
            {
                _logger.LogDebug("APIController.UpdatePatientComment() was called...");
                var updated = await _dbHandler.UpdatePatientCommentAsync(editedComment);
                if (updated)
                {
                    return Ok(editedComment);
                }
                else
                {
                    return BadRequest("Comment not updated.");
                }
            }
            catch
            {
                throw;
            }
        }

在我的服务中:

updatePatient(editedPatient: Patient): Observable<Patient> { //not working at all
        return this.http.post<Patient>(ConfigService.Config.apiBaseUrl + "/Patients/update", editedPatient).pipe(
            catchError(this.rHndlr.handleError("updatePatient", this.updatedPatient))
        )
    }
updatePatientComment(editedComment: PatientComment): Observable<PatientComment>{ //works (again) GREAT!
        return this.http.post<PatientComment>(ConfigService.Config.apiBaseUrl + "/Patients/comment/update", editedComment).pipe(
            catchError(this.rHndlr.handleError("updatePatientComment", this.updatedComment))
        )
    }

以及如何称呼它们:

updatePatient(updatedPatient: Patient): Promise<Patient> {
        this.loading = {
            loadingText: "Updating patient",
            errorText: "Comment update failed, try something else.",
            errorTextVisible: false
        }

        const promise = new Promise<Patient>((resolve, reject) => {
            this.patientSvc.updatePatient(updatedPatient).subscribe({ //NOT EVEN CLOSE TO WORKING!!!
                next: (data: Patient) => {
                    if (JSON.stringify(updatedPatient) === JSON.stringify(data)) {
                        console.log("Success updating patient!")
                    }
                },
                error: (err) => {
                    alert("Error updating patient data!\n" + JSON.stringify(err));
                },
                complete: () => {
                    resolve(this.patient);
                }
            })
        });
        return promise;
    }
updatePatientComment(editedComment: PatientComment): Promise<PatientComment> {
        this.loading = {
            loadingText: "Updating comment",
            errorText: "Comment update failed, try something else.",
            errorTextVisible: false
        }

        const promise = new Promise<PatientComment>((resolve, reject) => {
            this.patientSvc.updatePatientComment(editedComment).subscribe({ //WORKING!!!
                next: (data: PatientComment) => {
                    if(JSON.stringify(editedComment) === JSON.stringify(data)){
                        console.log("Success updating comment!");
                        this.commentChanged = false;
                    }
                },
                error: (err) => {
                    alert("Error updating comment! \n" + JSON.stringify(err));
                },
                complete: () => {
                    resolve(this.patientComment);
                }
            })
        });
        return promise;
    }

以及手边的两个对象:

export interface Patient {
    id: number;
    socialSecurityNumber: string;
    firstName: string;
    lastName: string;
    diagnosisId: number;
    riskAssessmentId: number;
    deceasedDate?: number;
    commentId: number;
    clinicId: number;    
    active: boolean;
    staffId: number;
}
export interface PatientComment {
    id: number,
    commentText: string,
    commentDate: Date,
    signature: string
}

(发布的对象是从相应类的 get 函数中检索到的相同对象,只是 lastName(对于 Patient)和 commentText(对于 PatientComment)略有改变) 我想我的问题是:我错过了一些明显的东西吗?可能是 Patient 对象的大小太大了吗?同样,在我看来,在我获得状态之前,调用甚至没有开始处理:更新 Patient 时为 400 ...并且后端中的 post 方法甚至没有被触发 - 对于 PatientComment 一切正常,我可以触发每当我调用端点时,后端方法的断点。我已经使用 Swagger 和 Postman 测试了 api,它们似乎都可以在那里工作(虽然我对使用它们中的任何一个都不是很有经验,但我想,所以我可能会遗漏一些东西)。有任何想法吗?

我已经使用 Swagger/Postman 触发了这两种 api 方法,并且我已经在 VS Code 中调试了这个过程——用谷歌搜索服务类中“catchError”提供的错误消息的每一部分:

{"headers":{"normalizedNames":{},"lazyUpdate":null},"status":400,"statusText":"错误请求","url":"https://localhost:62006/api/ Patients/update","ok":false,"name":"HttpErrorResponse","message":"Http 失败响应 https://localhost:62006/api/Patients/update: 400 Bad Request","error" :{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"出现一个或多个验证错误。","status":400,"traceId ":"00-f1e88aa13075736f6590b352c4afe68f-64f8c787e1bbcc8b-00","errors":{"Staff":["The Staff field is required."],"Clinic":["The Clinic field is required."],"Diagnosis" :["诊断字段是必需的。"],"PatientComment":["PatientComment 字段是必需的。"],"RiskAssessment":["RiskAssessment 字段是必需的。"]}}}

然后我应用了太多的解决方案甚至无法计算(大多数来自 stackoverflow 上的其他线程),即使它看起来很像一个 smiliar 问题。 两次调用的 api 地址(localhost:whatever)相同,并且绝对正确,并且端点已从后端复制/粘贴以防万一。 我尝试提供飞行前数据({headers: {'Content-Type':"application/json"}}),使用 .put 而不是 .post,更改端点地址设置,其他本地主机端口,JSON.stringify(editedPatient)作为身体......但没有任何效果(obv)。我唯一能够收集到的东西,因为后端的断点永远不会触发,这是一个与前端相关的问题......但在这一点上,我几乎不确定我自己的名字:P

【问题讨论】:

  • catch { throw; } ... 为什么?
  • 您可以发布 PatientPatientComment 的 C# 模型吗?我有一个怀疑。
  • 很抱歉这么晚才在这里回复...但是,所以...我抓住了 {throw;} 因为我需要尝试/抓住数据库交互,如果我不抛出那么项目就无法构建,因为“所有代码路径都不返回值”ofc,在未来,我最终会进行异常处理,这实际上会捕获并生成一个适当的异常(无论如何是这个想法)。
  • 照原样,它只是重新抛出异常(并使您的代码混乱)。所以,要么删除 try/catch 要么至少记录一些东西。

标签: c# json angular typescript api


【解决方案1】:

响应包含请求被拒绝的原因:

"errors": {
    "Staff": [
        "The Staff field is required."
    ],
    "Clinic": [
        "The Clinic field is required."
    ],
    "Diagnosis": [
        "The Diagnosis field is required."
    ],
    "PatientComment": [
        "The PatientComment field is required."
    ],
    "RiskAssessment": [
        "The RiskAssessment field is required."
    ]
}

pdatePatientAsync(Patient editedPatient)中设置断点,找出对象未完全填充的原因。

【讨论】:

  • 哇!这就是当你连续工作太多小时时会发生的事情……我什至无法正常阅读。尴尬。我还没有尝试过,但似乎这就是阻碍它的原因。我一到办公室就会试一试,肯定会将您的答案标记为正确的解决方案。不管是哪种 - 非常感谢您帮助我重新学习如何阅读 :)
【解决方案2】:

在错误响应中,它表示 Patient 类需要某些字段,因此当它尝试将响应主体绑定到端点的 editedPatient 参数时,您会收到 400 错误,然后才能进入方法。

所以我猜你很可能遗漏了帖子请求正文中的一些 Patient 属性。

【讨论】:

  • 是的......我不敢相信我让那个从我身边溜走,尤其是当它就在我眼皮底下的时候。非常感谢你(很抱歉用这些废话占用了你的时间)。
  • @dustylamborghini 哈哈,没关系,这是我开始编码时学到的第一件事,大多数时候解决方案就在你面前,你只是想太多了......我们都会犯这些错误
猜你喜欢
  • 1970-01-01
  • 2018-06-20
  • 2013-06-08
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多