ASP.NET Web API 有两种输出格式 XML 和 JSON,会根据发送的 Accept 标头决定回应的格式,而在没有指定或查无格式的情况下,会预设回应 JSON 格式的内容。
测试程式:
namespace Api{ [RoutePrefix("api/test")] public class TestController : ApiController { //测试API [HttpGet] [Route("live")] public List<Student> Live() { return new List<Student> { new Student { Id = 100, Name = "小明" }, new Student { Id = 101, Name = "小华" }, }; } } public class Student { public int Id { get; set; } public string Name { get; set; } }}
下列为 Postman 测试结果。
Accept: application/xml
Accept: application/json
接着试着在 Chrome 浏览器上直接输入 API 网址。
可以看到因为 Chrome 浏览器预设会发送 XML 的 Accept,所以 Web API 回传 XML 的资料,不过这样在开发时不是很方便,可以直接在浏览器上看到 JSON 格式的资料吗?
在 第一篇 的 Startup 内加入下方程式码,将 XML 的 Formatter 移除,这样 Web API 就会统一回应 JSON 格式的资料。
//移除 XML Formattervar appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
结果:
如果希望回传的 JSON 缩排换行,方便阅读,可以加入以下程式码。
//JSON 缩排config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
结果:
完整程式码:
[assembly: OwinStartup(typeof(Core.Startup))]namespace Core{ public partial class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //移除 XML Formatter var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); //JSON 缩排 config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; app.UseWebApi(config); } }}
结语:
今天介绍了如何控制 Web API 输出 XML 和 JSON 格式的资料,而移除 XML 和格式化是为了方便测试,正式上线后记得移除,确保 API 完整支持 XML 和 JSON,且输出的资料最小化,这篇就到这里,感谢大家观看。
参考文章:
如何让 ASP.NET Web API 无论任何要求都回应 JSON 格式
ASP.NET Web API 入门常用技巧