Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return json error msg in asp.net web api?

I would like to return a json errormessage but at the moment in fiddler I cannot see this in the json panel:

string error = "An error just happened"; JsonResult jsonResult = new JsonResult {      Data = error,      JsonRequestBehavior = JsonRequestBehavior.AllowGet }; response = Request.CreateResponse(HttpStatusCode.BadRequest, jsonResult.Data); 

how to do this?

like image 795
user603007 Avatar asked Mar 24 '14 10:03

user603007


People also ask

How do I return a JSON response in C#?

ContentType = "application/json; charset=utf-8"; Response. Write(json); Response. End(); To convert a C# object to JSON you can use a library such as Json.NET.

What is JsonResult .NET core?

An action result which formats the given object as JSON.

What is JsonResult in ASP NET MVC?

What is JsonResult ? JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format).


2 Answers

you can return JSON like below,

 return Request.CreateResponse<ResponseApiModel>(HttpStatusCode.BadRequest, response); 

I recommend to use IHttpActionResult on your method return type instead HttpResponseMessage, if your api's method return type is IHttpActionResult. you can return like;

 return Content(HttpStatusCode.InternalServerError, response); 

you can check also that link about best practice of error returning Especially @Daniel Little's answer is really useful.

I know the answer added to late but maybe stand someone in good stead.

like image 32
arslanaybars Avatar answered Sep 27 '22 16:09

arslanaybars


A few points:

If all you're looking to do is return an error response containing a simple error message, Web API provides a CreateErrorResponse method for that. So you can simply do:

return Request.CreateErrorResponse(HttpStatusCode.BadRequest,                                     "An error just happened"); 

This will result in the following HTTP response (other headers omitted for brevity):

HTTP/1.1 400 Bad Request Content-Type: application/json; charset=utf-8 Content-Length: 36  {"Message":"An error just happened"} 

If you want to return a custom object instead, then you use Request.CreateResponse like you were doing, but don't use the MVC JsonResult. Instead, just pass your object directly to CreateResponse:

var myError = new {     Data = "An error just happened",     OtherDetails = "foo bar baz" };  return Request.CreateResponse(HttpStatusCode.BadRequest, myError); 

Now, say you are doing this but you're not getting JSON back from the server. It is important to realize that Web API normally uses content type negotiation to determine what format to use when sending the response back. That means, it looks at the Accept header that was sent by the client with the request. If the Accept header contains application/xml, for example, then Web API will return XML. If the header contains application/json then it will return JSON. So, you should check that your client is sending the correct Accept header.

That said, there are ways to force Web API to always return data in a specific format if that is what you really want. You can do this at the method level by using a different overload of CreateResponse which also specifies the content type:

return Request.CreateResponse(HttpStatusCode.BadRequest, myError,      new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")); 

Alternatively, you can remove the XML formatter from the configuration altogether in your WebApiConfig file:

config.Formatters.Remove(config.Formatters.XmlFormatter); 

This will force Web API to always use JSON regardless of what the client asks for.

like image 128
Brian Rogers Avatar answered Sep 27 '22 16:09

Brian Rogers