jaffa
jaffa

Reputation: 27350

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);
        }

    }

Upvotes: 6

Views: 5563

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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" }
);

Upvotes: 14

Related Questions