简体   繁体   中英

How to return BadRequest response with custom error model? WEB API 2

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": {}
    }
}

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"
        });
    }
}

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