如何在 ServiceStack 中实现 JSONP 格式化程序
How to Implement the JSONP formatter in ServiceStack
目前在我的网站 API 下面提到的 class 已实现
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 实现?
ServiceStack 已经通过向 QueryString 添加 ?callback=cb
为所有服务内置 JSONP 支持,例如:http://techstacks.io/overview?callback=cb
这将在指定的 JS 回调中包装 JSON 响应,例如:
cb({...})
目前在我的网站 API 下面提到的 class 已实现
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 实现?
ServiceStack 已经通过向 QueryString 添加 ?callback=cb
为所有服务内置 JSONP 支持,例如:http://techstacks.io/overview?callback=cb
这将在指定的 JS 回调中包装 JSON 响应,例如:
cb({...})