6

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

    }

1 Answer 1

14
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" }
);
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry see above link in my post. I want to create content of JsonObject type.
Great, I was missing 'using System.Net.Http'. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.