首页 > 解决方案 > angular 8 客户端未命中 asp.net api 端点

问题描述

我正在尝试从 Angular 8 客户端调用 refreshToken 端点,但它似乎没有命中。任何人都可以发现这个问题。我什至尝试匹配参数的大小写,但没有任何区别。我已经验证 this.refreshLoginUrl 是正确的。是否与发送的参数序列或任何其他不匹配有关

客户端

getRefreshLoginEndpoint<T>(): Observable<T> {

        let header = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' });

        let params = new HttpParams()
            .append('refreshtoken', this.authService.refreshToken)
            .append('accesstoken', this.authService.accessToken)
            .append('username', this.authService.currentUser.userName)
            .append('userid', this.authService.currentUser.id)
           //.append('grant_type', 'refresh_token')
           //.append('scope', 'openid email phone profile offline_access roles')
           //.append('resource', window.location.origin);
        let requestBody = params.toString();
        return this.http.post<T>(this.refreshLoginUrl, requestBody, { headers: header })
        .pipe(catchError(error => {
            return this.handleError(error, () => this.getRefreshLoginEndpoint());
        }));
    }

服务器端

    public class RefreshTokenModel
    {
        public int UserID { get; set; }
        public string UserName { get; set; }
        public string AccessToken { get; set; }
        public string RefreshToken { get; set; }
    }

  [AllowAnonymous]
        [HttpPost("token/refresh")]
        [Produces("application/json")]
        public async Task<IActionResult> RefreshToken(RefreshTokenModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "Invalid request data"
                });
            }

            var token = await _identityService.RefreshToken(model);

            if (token == null)
            {
                return BadRequest(new OpenIdConnectResponse
                {
                    Error = OpenIdConnectConstants.Errors.InvalidGrant,
                    ErrorDescription = "Please check that your credentials are correct"
                });
            }

            return Ok(token);
        }

标签: angularasp.net-core

解决方案


不使用 httpParamas 发送参数,只是一个简单的对象

const params = {
     userID: this.authService.currentUser.id,
     userName:this.authService.currentUser.userName,
     accessToken:this.authService.accessToken,
     refreshToken:null
}
return this.http.post<T>(this.refreshLoginUrl, params)
    .pipe(catchError(error => {
        return this.handleError(error, () => this.getRefreshLoginEndpoint());
    }));

并在您的 api [FromBody] 中使用

public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenModel model){...}

注意:我认为 this.http 是 HttpClient,而不是过时的 Http


推荐阅读