我正在使用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());