I need to convert String response to Json response. But I have to use different way to fix my issue but I couldn't able to find any good solution for that.
if (response.IsSuccessStatusCode)
{
string successResponse = "Order Created Successfully with InterfaceRecordId : " order.WMWDATA.Receipts.Receipt.InterfaceRecordId " & ReceiptId : "
order.WMWDATA.Receipts.Receipt.ReceiptId;
_logger.LogInformation(successResponse);
return StatusCode((int)response.StatusCode, successResponse);
}
_logger.LogError(jsonResponse);
return StatusCode((int)response.StatusCode, jsonResponse);
I just need to send this successRespose as JSON response. Can you please help me to resolve this.
CodePudding user response:
Please have a read over Format response data in ASP.NET Core Web API. There are multiple possibilities, depending on what your exact requirements are.
The simplest option is to add [Produces] attribute to the controller action, specifying the type that's returned from the aciton:
[Produces("application/json")]
public IActionResult YourAction(int id) { ... }
The above action will return application/json even when the return type of the action is string.
However, it looks like you're returning two values in the string (InterfaceRecordId and ReceiptId). You can use built-in methods (such as Ok(), BadRequest(), Created(), NotFound(), etc) which convert the object to JSON and return a specific status code.
I would recommend returning an object containing both values, and use a convenience return method (Created() or CreatedAtAction()). The following returns an anonymous object and status code 201:
var successResponse = new
{
InterfaceRecordId = order.WMWDATA.Receipts.Receipt.InterfaceRecordId,
ReceiptId = order.WMWDATA.Receipts.Receipt.ReceiptId
}
return CreatedAtAction(nameof(YourAction), successResponse);
The CreatedAtAction (and Created) convenience methods return a 201 (created) HTTP Code - so the client will be able to infer that from the status code. And since it's returning an object (rather than a string), the return type defaults to application/json, so there's no need for the [Produces] attribute.
