WebAPI formatting errors as JSON

Vote:
 

I have implemented WebAPI in my EPiServer solution. I am having trouble with error handling. I would like my errors to return as some JSON along with the correct status code. No matter what I do, error sare returning an HTML error page. I have gon through a whole bunch of different options. This is what I think I need to do:

[HttpGet]
public HttpResponseMessage GetViewpoint(int id)
{
	var version = WebConfigurationManager.AppSettings["ApiVersion"];
	if (id == 99)
	{
		var error = new WebApiError("This id is BAD BAD BAD!");
		var apiErrorModel = new WebApiModel(HttpStatusCode.BadRequest, error) {Version = version};

		return this.Request.CreateResponse(apiErrorModel.StatusCode, apiErrorModel,
			new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
	}

	dynamic jObject = new JObject();
	jObject["Message"] = "This is a viewpoint";
	var apiModel = new WebApiModel("Success", jObject, HttpStatusCode.OK, version);

	return this.Request.CreateResponse(apiModel.StatusCode, apiModel);
}

But this still returns an HTML error page:

#263295
Sep 17, 2021 14:53
Vote:
 

did you check IIS friendly error message feature? that one should be turned off for the best experience here...

#263396
Sep 20, 2021 8:28
Vote:
 

I know this happens when you have your custom error page enabled globally. I would say try something like this to filter the API based error messages different from global errors.

<!-- Override it for paths starting with api (your WebAPI) -->
  <location path="api">
     <system.web>
        <customErrors mode="Off" />
     </system.web>
  </location>

Note, you can continue to use your global custom errors as you prefer. E.g. 

<!-- General for the application -->
  <system.web>
    <customErrors mode="RemoteOnly" defaultRedirect="YourCustomErrorPage.aspx"/>
  </system.web>

Hope this works. Please update how it goes.

~ Sujit

#263679
Sep 23, 2021 22:44
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.