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, Stephen
public partial class GenericServices
{
public object Any(Generic request)
{
try
{
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))
{
entity.ExecuteRuleSet(request.RulesetName);
}
else
{
session.ApplyRules();
}
var reqTypes = Request.AcceptTypes;
//todo: best way to determine formatter?
if(reqTypes.Contains("application/json"))
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);
throw;
}
}
}
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.