如何在 ServiceStack 中实现 JSONP 格式化程序
Posted
技术标签:
【中文标题】如何在 ServiceStack 中实现 JSONP 格式化程序【英文标题】:How to Implement the JSONP formatter in ServiceStack 【发布时间】:2015-06-14 08:28:24 【问题描述】:目前在我的 web API 中实现了下面提到的类
public class ServiceStackTextFormatter : MediaTypeFormatter
public ServiceStackTextFormatter()
JsConfig.DateHandler = JsonDateHandler.ISO8601;
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
我只想知道如何在 ServiceStack 中实现 JSNOP,我知道我们可以使用 Newtnsoft json 来实现它。我试过使用下面提到的代码,它工作正常。
public class FormatterConfig
public static void RegisterFormatters
(MediaTypeFormatterCollection formatters)
var jsonFormatter = formatters.JsonFormatter;
jsonFormatter.SerializerSettings = new JsonSerializerSettings
ContractResolver = new CamelCasePropertyNamesContractResolver()
;
formatters.Insert(0, jsonFormatter);
var jsonpFormatter =
new JsonpMediaTypeFormatter(formatters.JsonFormatter);
formatters.Insert(1, jsonpFormatter);
所以我只想知道如何使用 ServiceStack?
【问题讨论】:
【参考方案1】:ServiceStack 通过将?callback=cb
添加到QueryString 中,已经为所有服务内置了JSONP 支持,例如:http://techstacks.io/overview?callback=cb
这会将 JSON 响应包装在指定的 JS 回调中,例如:
cb(...)
【讨论】:
以上是关于如何在 ServiceStack 中实现 JSONP 格式化程序的主要内容,如果未能解决你的问题,请参考以下文章
如何在 JSON.NET 中实现自定义 JsonConverter?
如何在 jOOQ for MySQL 8 中实现 JSON_SET()