首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使Owin自身主机支持Json输出?

如何使Owin自身主机支持Json输出?
EN

Stack Overflow用户
提问于 2014-10-22 06:18:24
回答 1查看 11.7K关注 0票数 26

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

代码如下:

代码语言:javascript
复制
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);
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-23 05:54:35

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

代码语言:javascript
复制
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
config.Formatters.JsonFormatter.SerializerSettings =
new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver()
};

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

代码语言:javascript
复制
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
票数 43
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26497343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档