【问题标题】:how to post raw json data in angular 7如何在 Angular 7 中发布原始 json 数据
【发布时间】:2020-02-22 08:05:59
【问题描述】:

我想将用户名从 angular 发布到 asp.net web api。 我从服务器发布的方法是:

 [Route("CheckUserName")]
    [AllowAnonymous]
    [HttpPost]
    public async Task<IHttpActionResult> CheckUsernameExist([FromBody] string username){ //return true or false}

和角度

checkUserName(userName: string) {
return this.http.post(
  `${this.appConfig.apiEndpoint}/${CHECK_USER_NAME}`,{userName})
  .pipe(map(res => res['result']['status'] as boolean));}

{userName} 是发送到服务器的数据 但服务器端接收 null 我也测试数据:

userName,
{username:userName},
'"'+userName+'"',
,...

  checkUserName(userName: string) {
const headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
return this.http.post(
  `${this.appConfig.apiEndpoint}/${CHECK_USER_NAME}`, { userName },{ headers: headers })
  .pipe(map(res => res['result']['status'] as boolean));

}

我还使用邮递员进行测试并正确获取服务器端的数据

【问题讨论】:

    标签: json angular http-post


    【解决方案1】:

    以这种格式发送您的数据:

    {userName:userName}
    

    【讨论】:

    • 你也可以使用get方法。这样写你的api [Route("CheckUserName/{username}")] [AllowAnonymous] [HttpGet] public async Task CheckUsernameExist(string username)
    • 是的,我知道,但出于安全原因,我必须使用 Post Method。
    【解决方案2】:

    找了很久

           let reqHeaders = new HttpHeaders().set('Content-Type', 'application/json');
       return this.http.post(`${this.appConfig.apiEndpoint}/${CHECK_USER_NAME}`, JSON.stringify(userName), { headers: reqHeaders })
          .pipe(map(res => res['result']['status'] as boolean));
    

    answer

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-17
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 2013-01-24
      相关资源
      最近更新 更多