Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass content in response from Exception filter in Asp.net WebAPI?

Consider following code:

My problem is:

1) I can't seem to cast the errors to HttpContent

2) I can't use the CreateContent extension method as this doesn't exist on the context.Response.Content.CreateContent

The example here only seems to provide StringContent and I'd like to be able to pass the content as a JsobObject: http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

 public class ServiceLayerExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Response == null)
            {                
                var exception = context.Exception as ModelValidationException;

                if ( exception != null )
                {
                    var modelState = new ModelStateDictionary();
                    modelState.AddModelError(exception.Key, exception.Description);

                    var errors = modelState.SelectMany(x => x.Value.Errors).Select(x => x.ErrorMessage);

                    // Cannot cast errors to HttpContent??
                    // var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) {Content = errors};
                    // throw new HttpResponseException(resp);

                    // Cannot create response from extension method??
                    //context.Response.Content.CreateContent
                }
                else
                {
                    context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
                }                
            }

            base.OnException(context);
        }

    }
like image 241
jaffa Avatar asked Jun 18 '12 09:06

jaffa


People also ask

How do I return an exception from Web API?

Return InternalServerError for Handled Exceptionscs file and locate the Get(int id) method. Add the same three lines within a try... catch block, as shown in Listing 2, to simulate an error. Create two catch blocks: one to handle a DivideByZeroException and one to handle a generic Exception object.

How do I handle exceptions in asp net core Web API?

To handle exceptions we can use the try-catch block in our code as well as finally keyword to clean up resources afterward. Even though there is nothing wrong with the try-catch blocks in our Actions in Web API project, we can extract all the exception handling logic into a single centralized place.

Which of the following response is sent by Web API for uncaught exception?

When an action method in Web API throws an uncaught exception, the exception is translated to HTTP Status Code 500, i.e., “Internal Server Error.” If you use HttpResponseException, you can specify the status code you would like to return in the constructor of the HttpResponseException class.


1 Answers

context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
context.Response.Content = new StringContent("Hello World");

you also have the possibility to use the CreateResponse (added in RC to replace the generic HttpResponseMessage<T> class that no longer exists) method if you want to pass complex objects:

context.Response = context.Request.CreateResponse(
    context.Exception.ConvertToHttpStatus(), 
    new MyViewModel { Foo = "bar" }
);
like image 164
Darin Dimitrov Avatar answered Nov 15 '22 06:11

Darin Dimitrov