How to determine null result per web api action ?

Topics: ASP.NET Web API
Dec 6, 2012 at 8:52 PM

Is there a way to determine a null return value of an async action in action filters?

public class NoContent : ActionFilterAttribute
{
       
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
       
{
               
if (what? == null)
               
{ throw new HttpResponseException(HttpStatusCode.NoContent);
               
}
                
               
base.OnActionExecuted(actionExecutedContext);
       
}
}

Coordinator
Dec 6, 2012 at 11:59 PM

You can inspect the content of the response message from the context.

Daniel Roth

Dec 8, 2012 at 2:44 PM
Edited Dec 8, 2012 at 2:49 PM

Actually, my testing shows that actionExecutedContext.Response.Content would always hold non-null HttpResponseMessage object regardless of what the action returned.

I wonder if testing actionExecutedContext.Response.Content.Headers.ContentLength == null is sufficient to determine a No Content status code at this stage.

Can you please point me to a specific call ?

Thanks!

-Itai

Dec 10, 2012 at 5:41 AM
Edited Dec 10, 2012 at 5:49 AM

Hi Itai

You can call

ObjectContent content = response.Content as ObjectContent;
if(content != null && content.Value == null) {
   // action returned a null value
}
Dec 10, 2012 at 7:36 AM

Thanks! The following appears to work for me.

public class NoContent : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        ObjectContent content = actionExecutedContext.Response.Content as ObjectContent;
        if (content != null && content.Value == null)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NoContent);
            actionExecutedContext.Response = response;
        }
        
        base.OnActionExecuted(actionExecutedContext);
    }
}

So in general, is it OK to substitute a response message in an action filter with a different generic type? I mean are there any other dependencies on the original type that was intendant to be retuned?

BTW,  throwing new HttpResponseException(HttpStatusCode.NoContent); results with HTTP/1.1 500 which I didn’t expect… but I’m probably missing something here.