加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何使Owin自主主机支持Json输出?

发布时间:2020-12-15 23:12:53 所属栏目:asp.Net 来源:网络整理
导读:我正在使用Owin构建一个支持文件请求和web api的自托管服务器.但是,web api请求的输出始终为xml格式.如何配置owin以输出json? 代码如下: class Startup{ public void Configuration(IAppBuilder app) { app.UseFileServer(new FileServerOptions() { Reque
我正在使用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);
    }
}

解决方法

我已经找到答案了.所有必须做的是添加一个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());

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读