简体   繁体   中英

IActionResult not returning string response as string

I am migrating my web api's to .net core code.

This is my current api, which is correctly returning string as expected

[HttpPost]
public string ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber)
{
    return _ewpDataAccess.ValidateEwpInspectionNumber(ewpNumber, inspectionNumber);
}

This is how the response looks like in developer tool for it

在此处输入图像描述

Which is what is expected by my code. The api is properly returning string result.

Now, this is the migrated api where we are using IActionResult as return type

[HttpPost(nameof(ValidateEwpInspectionNumber))]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
public async Task<IActionResult> ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber)
{
    var response = await _ewpBusinessService.ValidateEwpInspectionNumberAsync(ewpNumber, inspectionNumber);
    return Ok(response);
}

But this api is not returning result as string. This is how the response looks.

在此处输入图像描述

You can see it is not same as the old api and because of which the angular code is not considering the response as string but an object.

I tried returning Content(response) and Content(response, 'text/plain') also but that too returned the same type of object.

Tried replacing IActionResult with ActionResult<string> , but no luck.

Is there any way to return direct string from IActionResult the way old api is returning?

Update

I checked that by default the Ok() returns response in json format only which is what I want, but for my response, since it is a plain text, it is setting the content type to text/plain .

So I tried to set the content type manually by using Content(response, 'application/json') but then it starts giving json parsing error

can't parse JSON. Raw result:

NOTEXISTS

So looks like it is not possible with .net core api to return string as json until it is actually a valid json.

Could you check to know if the API response is JSON or just Text? The screenshot you shared seems like the response is formatted as plain text and the old api has its response format as JSON. IF this is the case you may want to force the API to return JSON.

Return it as a JsonResult , you need to format it:

public async Task<IActionResult> ValidateEwpInspectionNumber(string ewpNumber, string inspectionNumber)
{
    var response = await _ewpBusinessService.ValidateEwpInspectionNumberAsync(ewpNumber, inspectionNumber);
    return new JsonResult(response);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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