【问题标题】:How to correctly pass header parameter in Angular?如何在Angular中正确传递标头参数?
【发布时间】:2020-09-07 06:38:22
【问题描述】:

在 Angular 中传递我的标头参数时遇到一些问题。我从我的 API 得到的错误是“需要会话 ID”,如下所示。 这是我的终点:

       [HttpDelete("")]

        public IActionResult EndSession(
            [Required(ErrorMessage = "Session Id is required.")]
            [StringLength(maximumLength: 36, MinimumLength = 36, ErrorMessage  = "Session Id should be 36 characters long.")]
            [FromHeader] string sessionId)

这是我在 Angular 应用程序中的服务方法:

public async EndSession(sessionId: string): Promise<boolean> {

const headers = new HttpHeaders()
  .set(sessionId , 'string')

this.appSettings = (await this.configService.loadConfig().toPromise());

return this.http.delete<boolean>(this.appSettings.apiSetting.apiAddress + this.apiRoute, { headers })
  .pipe(
    retry(1),
    catchError(this.handleError)
)
  .toPromise()

在我调用此方法的组件中,我将 sessionId 硬编码如下:

  export class AppBarHorizontalComponent implements OnInit {
  sessionId = "4CB3C85B-2C11-48AE-8D51-1DC30242A743"
  constructor(private oauthService: OAuthService, private userService: UserSessionService) {  }

public logout(): void {
this.userService.EndSession(this.sessionId);
//this.oauthService.logOut(false);

我期望 sessionId 作为标头参数正确传递,因此 api 方法可以正常执行。

【问题讨论】:

标签: c# angular typescript asp.net-core-webapi


【解决方案1】:

发现我的错误。在我设置标题的服务方法中,我混淆了参数。那是:

const headers = new HttpHeaders()
  .set(sessionId , 'string')

改为:

const headers = new HttpHeaders()
  .set('sessionId', sessionId)

【讨论】:

    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2020-09-28
    • 2019-03-28
    • 1970-01-01
    相关资源
    最近更新 更多