Returning JSON error message, IActionResult

asp.net core return error message
.net core return status code with message
iactionresult return types
get status code from iactionresult
asp.net core return internal server error with message
asp.net core return unauthorized with message
web api return status code with message
statuscoderesult with message

I have an API controller endpoint like:

public IHttpActionResult AddItem([FromUri] string name)
{
    try
    {
        // call method
        return this.Ok();
    }
    catch (MyException1 e)
    {
        return this.NotFound();
    }
    catch (MyException2 e)
    {
        return this.Content(HttpStatusCode.Conflict, e.Message);
    }
}

This will return a string in the body like "here is your error msg", is there any way to return a JSON with 'Content'?

For example,

{
  "message": "here is your error msg"
}

Just construct the desired object model as an anonymous object and return that.

Currently you only return the raw exception message.

public IHttpActionResult AddItem([FromUri] string name) {
    try {
        // call service method
        return this.Ok();
    } catch (MyException1) {
        return this.NotFound();
    } catch (MyException2 e) {
        var error = new { message = e.Message }; //<-- anonymous object
        return this.Content(HttpStatusCode.Conflict, error);
    }
}

Handling errors in ASP.NET Core Web API, Simply returning a 404 status code (with no response body) for an API route that A missing ProductId results in a 400 status code plus a JSON response body public async Task<IActionResult> GetProduct(GetProductRequest request)  Hi, Presently in every web api method ( in vNext) I am converting data to json and returning the data. ie for example i have to return List data ; I would return it as return Json(data) to convert it to json object.

In your case you need to return an object, where it should be like below, I didn't executed but please try

public class TestingMessage
{
    [JsonProperty("message")]
    public string message{ get; set; }
}

public IHttpActionResult AddItem([FromUri] string name)
{
    TestingMessage errormsg=new TestingMessage();
    try
    {
        // call service method
        return this.Ok();
    }
    catch (MyException1)
    {
        return this.NotFound();
    }
    catch (MyException2 e)
    {
        string error=this.Content(HttpStatusCode.Conflict, e.Message);
        errormsg.message=error;
        return errormsg;
    }
}

Controller action return types in ASP.NET Core web API, iactionresult return types iactionresult return json asp.net core return error message asp.net core return internal server error with message get status code from  You can easily return JavaScript Object Notation (JSON) content from your application by using the JsonResult class (short method: Json()). public IActionResult JsonResult() { return Json(new { message = "This is a JSON result.", date = DateTime.Now }); } ContentResult

1) the easiest way: You can return directly whichever object you want, and it will be serialized as JSON. It can even be an anonymous class object created with new { }

2)

return new HttpResponseMessage(HttpStatusCode.BadRequest)
    {
        Content = new ObjectContent(typeof(ErrorClass), errors, new JsonMediaTypeFormatter())
    };

Returning JSON error message, IActionResult, messages. Note that the CreateErrorResponse method creates an HttpError object and then wraps it inside an HttpResponseMessage object. When multiple return types are possible, it's common to mix an ActionResult return type with the primitive or complex return type. Either IActionResult or ActionResult<T> are necessary to accommodate this type of action. Several samples of multiple return types are provided in this document. Return IEnumerable<T> or IAsyncEnumerable<T>

return Json(new {message = e.Message});

IActionResult Vs ActionResult, Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message. Actions can return results that are formatted in a particular format, regardless of client preferences. For example, returning JsonResult returns JSON-formatted data. Returning ContentResult or a string returns plain-text-formatted string data. An action isn't required to return any specific type. ASP.NET Core supports any object return value.

How to handle errors in ASP.NET Web API, Write the serialized return value into the response body; return 200 (OK). In-depth technical articles focusing on .NET Core, ASP.NET MVC, Web API and Microsoft Azure

Action Results in Web API 2, Some Action Results merely return an HTTP status code. NET Core uses JSON for responses, but the request Accept header can specify as XML) and the server will attempt to return the response in the specified format. 1) the easiest way: You can return directly whichever object you want, and it will be serialized as JSON. It can even be an anonymous class object created with new { } 2) return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new ObjectContent(typeof(ErrorClass), errors, new JsonMediaTypeFormatter()) };

IActionResult and ActionResult, Your action method should return either the specific result type (for instance, JsonResult ) or IActionResult . Returning JSON-formatted data: // GET: api/​authors  Returning an IActionResult is akin to returning an System.Object or Variant. We loose all of the type data needed by the compiler to ensure you are returning the correct thing. And needed by IDL generators such as RAML and Swagger to produce accurate response definitions.

Comments
  • Have you tried JsonResult?
  • Here you go stackoverflow.com/a/9777889/2130976
  • The best way would be to use ExceptionFilter and return generic model of ErrorResponse from there
  • @frogcoder nope, can you provide an example please