Pregunta

Requirement:

I am looking for a way to return an empty JSON object (such as {}) when the return type of my ServiceStack service method is void.

Reasoning:

The reason for wanting to return an empty JSON object for void types is due to the way jQuery handles content type application/json. As discussed here jQuery will throw an error when a 200 - OK status is received with no content. Which is what is currently returned for void.

Foreseen issues:

I am hoping there is an easy way to serialise void to {}.

  • If this is possible, would there be adverse consequences for doing this?
  • Would it affect the ServiceStack c# client when it expects void?
¿Fue útil?

Solución

I found the simple solution was to override the OnAfterExecute method in my custom ServiceStack ServiceRunner.

If there is no response (because the method returned void) and the ContentType is application/json then send an empty object.

public override object OnAfterExecute(IRequestContext requestContext, object response)
{
    if(response == null && requestContext.ContentType == "application/json")
        response = new {};

    return base.OnAfterExecute(requestContext, response);
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top