0

.NET MVC application that contains a Web Api 2 controller. After some google searchs, I understand that this is a correct way of handling errors in the api controller, by throwing HttpResponseException with an appropiate status code:

controller action method:

[System.Web.Http.Authorize]
public IHttpActionResult GetEntities() {
    var entsDb = db.MyEntities;

    /*
    //uncomment this block to test exception throw
    var response = new HttpResponseMessage(HttpStatusCode.NotFound) {
        Content = new StringContent("some error message", System.Text.Encoding.UTF8, "text/plain"),
        StatusCode = HttpStatusCode.NotFound
    };
    throw new HttpResponseException(response);
    */

    Dictionary<int, string> ents = entsDb.ToDictionary(k => k.id, v => v.name);
    return Ok(ents);
}

Then in consumer I can catch the exception and access the message etc. Consumer request:

    using (var client = new HttpClient()) {
        client.BaseAddress = new Uri(BaseAddress);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token.Access_Token);

        HttpResponseMessage response = await client.GetAsync("Api/GetEntities/");

        if (response.IsSuccessStatusCode) {
            Dictionary<int, string> listEnts = await response.Content.ReadAsAsync<Dictionary<int, string>>();
            return listEnts;
        }
        else {
            var s = response.Content.ReadAsStringAsync();
            s.Wait();
            throw new Exception("An error ocurred. Server response: "+s.Result);
        }
    }

In the above code, if I uncomment the exception block (in controller action method) it works as expected and the consumer gets the exception and can access its message etc.

This is working ok in development, but when I deploy the mvc/webapi project to the production server, whenever there is an error, instead of receiving my exception I just get a message "The page cannot be displayed because an internal server error has ocurred"

I guess this is because of the web.Release.config configuration that changes the "debug" switch on production server, with this line in Web.Release.config:

<compilation xdt:Transform="RemoveAttributes(debug)"/>

so with this configuration, in dev it will show detailed errors, but in production it will show generic error.

but I have no idea how to solve it. is there any way to make it return generic errors when in production server for mvc requests, but not for WebApi requests? and by the way, is this really a correct way of handling errors in WebApi?

**UPDATE: ** ok apparently my guess was not valid. I have re-deploy it with that line in web.release.config removed and it does the same. Also, If I run the webapi in localhost but on release mode, it works. So it just dont work on the server. maybe some IIS parameter or something?

1 Answer 1

0

ok, I finally located the error, it was in the web.config. I put it here in case it helps somebody...

following this post Is it possible to use custom error pages with MVC site but not Web API?

In my web.config I had added custom error pages like that:

<httpErrors existingResponse="Replace" defaultResponseMode="ExecuteURL" defaultPath="/Error/Index" errorMode="Custom">
  <remove statusCode="404"/>
  <remove statusCode="400"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
  <error statusCode="400" responseMode="ExecuteURL" path="/Error/Forbidden" />
</httpErrors>

and then I had this block so that api calls ignore the custom error pages and return the original error, as read here

  <location path="Api">
    <system.webServer>
      <validation validateIntegratedModeConfiguration="false" />
      <httpErrors errorMode="DetailedLocalOnly" existingResponse="PassThrough" >
         <clear/>
      </httpErrors>
    </system.webServer>
  </location>

I just had to remove the line <clear/> and everything works now.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.