【问题标题】:How to make Owin self host support Json output?如何让 Owin 自己的主机支持 Json 输出?
【发布时间】:2015-04-30 09:36:27
【问题描述】:

我正在使用 Owin 构建一个支持文件请求和 Web api 的自托管服务器。但是 web api 请求的输出总是 xml 格式。如何配置owin以json格式输出?

代码如下:

class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseFileServer(new FileServerOptions()
        {
            RequestPath = PathString.Empty,
            FileSystem = new PhysicalFileSystem(@".\files")
        });

        // set the default page
        app.UseWelcomePage(@"/index.html");

        HttpConfiguration config = new HttpConfiguration();

        config.Routes.MapHttpRoute
        (
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional } 
        );

        app.UseWebApi(config);
    }
}

【问题讨论】:

  • 当您发出生成 XML 的请求时,您要发送哪些标头?您是否发送指定 JSON 的 Accept 标头?
  • 标头如下:Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8

标签: asp.net


【解决方案1】:

我自己找到了答案。所要做的就是添加一个 json 格式化程序,如下所示:

config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

如果需要将枚举转换为字符串,请将 StringEnumConverter 添加到设置中。

config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2021-02-23
    • 1970-01-01
    • 2017-01-03
    • 1970-01-01
    相关资源
    最近更新 更多