【问题标题】:Angular 2 - Unexpected token < in JSON at position 0 - WebAPI [HttpPost]Angular 2 - 位置 0 的 JSON 中的意外令牌 < - WebAPI [HttpPost]
【发布时间】:2017-05-11 11:39:18
【问题描述】:

我正在尝试从 Angular 2 http 服务调用我的 POST 端点(ASP.NET WebAPI),但该端点根本没有被命中。我已经阅读了几篇文章,但没有一篇有效。

从我的 angular 2 组件中,我将我的服务称为

saveCarAuction(): void {
    let respone: ResponseObject;
    this.auctionservice.saveCarAuction(this.auction).subscribe(resp => {
        respone = resp;
    }, error => this.onError(error));
}

在拍卖服务中,我有

saveCarAuction(auction: CarAuction): Observable<ResponseObject> {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    var api: string = '/CarAuction';
    var url: string = this.baseApiPath + api;
    return this.http.post(url, JSON.stringify(auction), options)
        .map((res: Response) => res.json());
}

在我的 Web API 控制器中,我有

[HttpPost]
[Route("api/CarAuction")]
[ActionName("PostCarAuction")]
public IHttpActionResult PostCarAuction([FromBody]CarAuctionViewModel carAuction)
{
    ResponseObject response = new ResponseObject() {ResponseType = ResponseType.Success.ToString()};
    //some action
    return Ok(Utility.SerializeObject(response));
}

我的服务调用的最终 URL 是

http://localhost:53796/api/CarAuction

问题是,如果我在操作中设置断点,它将不会被调用。我尝试以不同于我的服务的方式传递数据,如下所示:

JSON.stringify({ carAuction: auction})

我也尝试通过属性路由来调用它(尽管我不喜欢那样),但这也不起作用。我试图在我的发布操作中接收一个简单的 json 字符串并反序列化并尝试更新返回类型,但似乎它决定玩一个棘手的游戏。

我的控制台中所有请求(和更改)的响应如下

我现在真的想不出让这个简单的场景成功运行的想法。

编辑 1: 我已经包含了我要传递给我的 API 的 json

{
    "carAuction": {
        "carPlateNumber": null,
        "carAuctionId": null,
        "sellerUserId": null,
        "carMakeId": null,
        "carModelId": null,
        "carColorId": null,
        "carType": null,
        "manufacturerYear": 2002,
        "manufacturerMonth": 4,
        "carMileage": 475000,
        "ownershipCount": 3,
        "ownershipType": null,
        "comments": null,
        "notes": null,
        "terms": null,
        "coverPhotoUrl": null,
        "salePublicationDateTime": null,
        "saleEndDateTime": null,
        "auctionType": null,
        "carbidPercentage": null,
        "saleType": null,
        "isHiddenAuction": false,
        "intervalBid": 0,
        "minimumPrice": 0,
        "contactPersonFullName": null,
        "contactPersonCompany": null,
        "contactPersonPhone": null,
        "contactPersonFax": null,
        "contactPersonWebsite": null,
        "contactPersonEmail": null,
        "contactPersonAddress": null,
        "hasAuctionEnded": false,
        "carLocation": null,
        "carMake": null,
        "carModel": null,
        "carColor": null,
        "carAuctionMedia": [],
        "id": "3F8184F7-37F4-4BD9-8B32-FDB8F65D5AB3",
        "appCultureId": null,
        "createdDate": null,
        "createdBy": null,
        "isActive": true,
        "modifiedDate": null,
        "modifiedBy": null
    }
}

【问题讨论】:

  • 分享您的auction 值,您正在进入saveCarAuction 函数?
  • 我已经包含了我使用这种格式传递给 API 的 json:JSON.stringify({ car​​Auction:auction }),它是有效的 JSON
  • @AliBaig baseApiPath 是什么?
  • 在这篇文章中查看我的答案:有一个工作示例可能对您有所帮助:stackoverflow.com/questions/41337145/…

标签: json angular asp.net-web-api http-post angular2-services


【解决方案1】:

您应该使用network tab 检查来自服务器的响应并将其附加到您的问题中。 看起来您的 JSON-Response 已损坏。当在发送输出之前打印错误消息或没有发送任何内容时,通常会发生这种情况。

【讨论】:

    【解决方案2】:

    我的猜测是您将所有请求重定向到index.html,或者您正在接收自定义的404 页面。尝试在浏览器中访问http://localhost:53796/api/CarAuction 并检查响应。

    非预期的令牌

    这几乎总是指试图解析为JSON 的html 页面。您发布的响应图像不是您从服务器获得的响应。您应该检查网络选项卡。

    【讨论】:

      【解决方案3】:

      看起来您的 ASP.NET Web API 返回的响应没有 JSON 格式。

      例如,您的 Web API 返回如下字符串值:

      bar
      

      但您需要以以下格式返回响应:

      {foo: 'bar'}
      

      所以你的回复应该是这样的:

      [HttpPost]
      [Route("api/CarAuction")]
      [ActionName("PostCarAuction")]
      public IHttpActionResult PostCarAuction([FromBody]CarAuctionViewModel carAuction)
      {
          ResponseObject response = new ResponseObject(){ResponseType = 
              ResponseType.Success.ToString()};
          return Ok(new {foo = response});
      }
      

      在上面的方法中,我们返回anonymous type,但是,我们可以返回DTO object

      return Ok(new PersonDto() { Name = response });
      

      【讨论】:

        猜你喜欢
        • 2016-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-05
        • 2021-09-12
        • 2018-10-17
        相关资源
        最近更新 更多