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

Posted by jaffa on Stack Overflow See other posts from Stack Overflow or by jaffa
Published on 2012-06-18T09:08:48Z Indexed on 2012/06/18 9:16 UTC
Read the original article Hit count: 231

Filed under:
|

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

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

    }

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about asp.net-web-api