JProgrammer
JProgrammer

Reputation: 2800

Returning a odata 4 error in ASP.NET Core

I am using Microsoft.AspNetCore.OData

During a patch operation we validate that there is no duplicates in the system and if so I want to return a 400 to the client with a correctly formatted Odata 4 error

Such as

public async Task<IActionResult> Patch([FromODataUri] int key, [FromBody] Delta<User> patch)
{
  return BadRequest("Duplicate email address");
}

I am expecting the json body to be

{
  "error": {
    "code": "400",
    "message": "Duplicate email address"
  }
}

However I receive

{
  "@odata.context":"https://localhost:3200/odata/$metadata#Edm.String",
  "value":"Duplicate email address"
}

Upvotes: 0

Views: 235

Answers (1)

Yinqiu
Yinqiu

Reputation: 7190

You can change your code like below:

var statusCode = (int)HttpStatusCode.BadRequest;
return BadRequest(new ODataError { ErrorCode = statusCode.ToString(), Message = "Duplicate email address" });

Result: enter image description here

Upvotes: 1

Related Questions