简体   繁体   English

从Controller返回时,字符串不充当有效的json对象

[英]String does not act as valid json object when returned from Controller

I'm trying to read a string from a json response however I get an error: 我正在尝试从json响应中读取字符串,但是出现错误:

SyntaxError: Unexpected token c in JSON at position SyntaxError:JSON中位置意外的令牌c

I have a controller which returns a guid as a string from the DB 我有一个控制器,它从数据库返回一个guid作为字符串

[HttpPost("TransactionOrderId/{id}")]
public async Task<string> TransactionOrderId(int id)
{
    return await this._service.GetTransactionOrderId(id);
}

In my Angular 2 application I'm subscribing to my provider which has trouble parsing my response from my server. 在我的Angular 2应用程序中,我正在订阅提供程序,该提供程序在解析来自服务器的响应时遇到问题。

this.meetingsProvider.getTransactionOrderId(this.meetingId).subscribe((transactionId: string) => {
    this.transactionOrderId = transactionId;
});

And My Provider code looks like so: 我的提供者代码如下所示:

getTransactionOrderId(meetingId: number): Observable<string> {

    const headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return  this.http.post(`${this.apiUrl}/${this.route}/transactionOrderId/${meetingId}`, null, {
        headers: headers
    }).map(res => <string>res.json());
}

My Server Responds with the proper transaction order id the response looks like so: 我的服务器以正确的交易订单ID响应,响应如下所示:

status: 200
statusText: "OK"
type: 2
url: "http://localhost/api/meetings/transactionOrderId/4"
_body: "0c290d50-8d72-4128-87dd-eca8b58db3fe"

I have other api calls using the same code that return bool which return fine, but when I try to return string I get a parsing error why? 我还有其他使用相同的代码返回bool的api调用,但返回的布尔值很好,但是当我尝试返回字符串时,为什么会出现解析错误?

That's not a valid JSON object, that's why you get that error. 那不是有效的JSON对象,所以才收到该错误。 A JSON object starts with { and ends with } . JSON对象以{开头,以}结尾。

If you want to be able to JSON-deserialize that, use: 如果您希望能够对其进行JSON反序列化,请使用:

public async Task<JsonResult> TransactionOrderId(int id)
{
    return Json(await this._service.GetTransactionOrderId(id));
}

Note that if you return anything that is not a string, ASP.NET Core should JSON-serialize it (that's the default serializer anyway). 请注意,如果返回的不是字符串,则ASP.NET Core应该对其进行JSON序列化(无论如何,这是默认的序列化程序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM