Stephen Stephen - 1 year ago 92
JSON Question

How to determine at runtime the accept type in a ServiceStack request

I'm using ServiceStack to wrap a component that only returns xml or json (as string) and am wondering how I can differentiate in my service code whether to call the toJson() or toXml() methods of the 3rd party object?

The IRequest object exposes an AcceptTypes array that may contain "application/json" or "application/xml" or "text/xml", is there a prefered way to make absolutely sure what format they are requesting and base my decision off of that?

Thank you,

public partial class GenericServices
public object Any(Generic request)
var response = new GenericResponse();

var ruleAppRef = new CatalogRuleApplicationReference(Keys.ServiceEndpoint, request.RuleApp);
using (var session = new RuleSession(ruleApplicationReference: ruleAppRef))
var entity = session.CreateEntity(request.EntityName, request.Data);
if (!string.IsNullOrWhiteSpace(request.RulesetName))

var reqTypes = Request.AcceptTypes;
//todo: best way to determine formatter?
response.Result = entity.GetJson();
if (reqTypes.Contains("application/xml") || reqTypes.Contains("text/xml"))
response.Result = entity.GetXml();
return response;
catch (Exception exception)
_log.Error("GenericServices", exception);


Answer Source

ServiceStack calculates the most appropriate ResponseType to return and populates it in IRequest.ResponseContentType.

So you can determine it with:

response.Result = Request.ResponseContentType.MatchesContentType(MimeTypes.Xml)
    ? entity.GetXml()
    : entity.GetJson();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download