-1

I want to return below json with BadRequest

{
    "error": {
        "code": "BAD_REQUEST_ERROR",
        "description": "frId is/are not required and should not be sent",
        "source": null,
        "step": null,
        "reason": null,
        "metadata": {}
    }
}
Mayur Patil
  • 63
  • 1
  • 7

1 Answers1

-1

You can make a class to encapsulate the response object like this:

class Error
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string Source { get; set; }
    public string Step { get; set; }
    public string Reason { get; set; }
    public object Metadata { get; set; }
}

Then you can return a instance of that object like this:

[HttpGet]
public IActionResult SomeGetReq()
{
    try
    {
        return Ok(someService.SomeMethod());
    }
    catch (Exception e)
    {
        // you can use e here
        return BadRequest(new Error
        {
            Code = "BAD_REQUEST_ERROR",
            Description = "frId is/are not required and should not be sent"
        });
    }
}
Valeriu Seremet
  • 558
  • 1
  • 7
  • 17
  • BadRequest() constructor accepts string format...its not accepting class object.. :/ – Mayur Patil Jun 09 '20 at 08:16
  • Make sure your function returns [IActionResult](https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-3.1#:~:text=IActionResult%20type,represent%20various%20HTTP%20status%20codes.&text=Alternatively%2C%20convenience%20methods%20in%20the,ActionResult%20types%20from%20an%20action.) – Valeriu Seremet Jun 09 '20 at 08:41