1 public static class WebApiConfig 2 { 3 public static void Register(HttpConfiguration config) 4 { 5 // Web API 配置和服务 6 7 // Web API 路由 8 config.MapHttpAttributeRoutes(); 9 10 config.Routes.MapHttpRoute( 11 name: "DefaultApi", 12 routeTemplate: "api/{controller}/{id}", 13 defaults: new { id = RouteParameter.Optional } 14 ); 15 16 config.Routes.MapHttpRoute( 17 name: "ActionApi", 18 routeTemplate: "{controller}/{action}/{id}", 19 defaults: new { id = RouteParameter.Optional } 20 ); 21 22 config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json"); 23 config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"); 24 25 } 26 }
WebAPI 只使用JSON格式响应
1 public static class WebApiConfig 2 { 3 public static void Register(HttpConfiguration config) 4 { 5 // Web API 配置和服务 6 7 // Web API 路由 8 config.MapHttpAttributeRoutes(); 9 10 config.Routes.MapHttpRoute( 11 name: "DefaultApi", 12 routeTemplate: "api/{controller}/{id}", 13 defaults: new { id = RouteParameter.Optional } 14 ); 15 16 config.Routes.MapHttpRoute( 17 name: "ActionApi", 18 routeTemplate: "{controller}/{action}/{id}", 19 defaults: new { id = RouteParameter.Optional } 20 ); 21 22 config.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 23 } 24 }
使用方式
http://localhost:8081/api/home?$format=json
http://localhost:8081/api/home?$format=xml
参考资料:https://code.msdn.microsoft.com/Support-format-in-ASPNET-e3785b2a