Try our conversational search powered by Generative AI!

WebAPI formatting errors as JSON


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:

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:

Sep 17, 2021 14:53

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

Sep 20, 2021 8:28

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">
        <customErrors mode="Off" />

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

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

Hope this works. Please update how it goes.

~ Sujit

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.