【问题标题】:How to Implement the JSONP formatter in ServiceStack如何在 ServiceStack 中实现 JSONP 格式化程序
【发布时间】: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?

【问题讨论】:

    标签: c# jsonp servicestack


    【解决方案1】:

    ServiceStack 通过将?callback=cb 添加到QueryString 中,已经为所有服务内置了JSONP 支持,例如:http://techstacks.io/overview?callback=cb

    这会将 JSON 响应包装在指定的 JS 回调中,例如:

    cb({...})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-29
      • 2013-07-09
      • 1970-01-01
      • 2012-06-14
      • 2013-09-19
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多