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

Consider the following code:

My problem:

1) I cannot submit errors in HttpContent

2) I can not use the CreateContent extension method, since this does not exist in the context. Response.Content.CreateContent

Only StringContent can serve as an example here, and I would like 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);
        }

    }
+5
source share
1 answer
context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
context.Response.Content = new StringContent("Hello World");

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

context.Response = context.Request.CreateResponse(
    context.Exception.ConvertToHttpStatus(), 
    new MyViewModel { Foo = "bar" }
);
+12
source

All Articles