[英]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? 我正在使用ServiceStack包装仅返回xml或json(作为字符串)的组件,并且想知道如何在服务代码中区分是调用第三方对象的toJson()还是toXml()方法?
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? IRequest对象公开了一个其中可能包含“ application / json”或“ application / xml”或“ text / xml”的AcceptTypes数组,有没有一种首选的方法来绝对确定它们请求的格式并以此为依据呢?
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
. ServiceStack计算最适合返回的ResponseType并将其填充在
IRequest.ResponseContentType
。
So you can determine it with: 因此,您可以通过以下方式确定它:
response.Result = Request.ResponseContentType.MatchesContentType(MimeTypes.Xml)
? entity.GetXml()
: entity.GetJson();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.