Client does not receive custom HttpResponseException from ApiController

I created an exception filter for my actions with the web API controller, but it seems to do nothing (even if it calls a call).

Attribute

public class ExceptionHandlerAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        context.Response = new HttpResponseMessage(HttpStatusCode.BadRequest);
        context.Response.Content = new StringContent("My content");
        context.Response.ReasonPhrase = "My reason";
    }
}

I also tried:

public override void OnException(HttpActionExecutedContext context)
{
    throw new HttpResponseException(
        new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("The content"),
            ReasonPhrase = "The reason"
        });
}

controller

[ExceptionHandler]
public class MyController : ApiController
{
    [Route("MyRoute"), HttpGet]
    public MyModel Index() {
        // code causing exception
    }
}

WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new ExceptionHandlerAttribute());
    }
}

However, when an exception occurs, the client receives this:

Exception message

+4
source share
2 answers

You need to throw HttpResponseExceptionwith a response from your exception filter:

public override void OnException(HttpActionExecutedContext context)
{
    throw new HttpResponseException(
        new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("The content"),
            ReasonPhrase = "The reason"
        });
}

Here's more information on how to handle exceptions in the web interface .

+1
source

your side API codes are ok. but getting the response should be like this (using a WebException capture):

string getResponse(WebRequest request, out exceptionOccured)
{
    exceptionOccured = false;
    try
    {
        HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
        var stream = resp.GetResponseStream();
        using (var reader = new StreamReader(stream))
        {
            return reader.ReadToEnd();
        }
    }
    catch (WebException ex)
    {
        exceptionOccured = true;
        using (var stream = ex.Response.GetResponseStream())
        {
            using (var reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }
    }
    catch (Exception ex)
    {
        exceptionOccured = true;
        // Something more serious happened
        // like for example you don't have network access
        // we cannot talk about a server exception here as
        // the server probably was never reached
        return ex.Message;
    }
}
0

Source: https://habr.com/ru/post/1598174/


All Articles