[C#][ASP.NET] Web API 开发心得 (3) - 统一回应 JSON 格式的资料

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

http://img2.58codes.com/2024/20106865i1kdxIUlFy.jpg

Accept: application/json

http://img2.58codes.com/2024/20106865KXs8F7gxNh.jpg

接着试着在 Chrome 浏览器上直接输入 API 网址。

http://img2.58codes.com/2024/20106865tjC1bIJtJL.jpg

可以看到因为 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);

结果:

http://img2.58codes.com/2024/201068655n46MydZxP.jpg

如果希望回传的 JSON 缩排换行,方便阅读,可以加入以下程式码。

//JSON 缩排config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

结果:

http://img2.58codes.com/2024/20106865u58f3XCwxl.jpg

完整程式码:

[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 入门常用技巧


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章