我使用ServiceStack来包装一个只返回xml或json(作为字符串)的组件,并且想知道如何在服务代码中区分是否调用第3个方法的toJson()或toXml()方法党对象?
IRequest对象公开一个AcceptTypes数组,该数组可能包含" application / json"或" application / xml"或" text / xml",是否有一种首选方式可以绝对确定他们要求的格式,并根据该决定做出决定?
谢谢你, 斯蒂芬
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;
}
}
}
答案 0 :(得分:2)
ServiceStack计算最合适的ResponseType,并在IRequest.ResponseContentType
中填充它。
所以你可以用:
来确定它response.Result = Request.ResponseContentType.MatchesContentType(MimeTypes.Xml)
? entity.GetXml()
: entity.GetJson();