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?
JsonResult is a MVC concept. It does not work in Web API. One way to explicitly return json content is to use the class I created in this answer https://stackoverflow.com/a/20504951/6819
Add config.Formatters.Remove(config.Formatters.XmlFormatter); line in your WebApiConfig file
You can directly set the status code of the current HTTP response through Response property
you can return JSON like below,
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;
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.
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:This will result in the following HTTP response (other headers omitted for brevity):
If you want to return a custom object instead, then you use
Request.CreateResponse
like you were doing, but don't use the MVCJsonResult
. Instead, just pass your object directly toCreateResponse
: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 theAccept
header containsapplication/xml
, for example, then Web API will return XML. If the header containsapplication/json
then it will return JSON. So, you should check that your client is sending the correctAccept
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:Alternatively, you can remove the XML formatter from the configuration altogether in your
WebApiConfig
file:This will force Web API to always use JSON regardless of what the client asks for.