在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数,只要在WebApiConfig里添加如下三行红色粗体代码即可:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Net.Http.Formatting; namespace ProjectManagementWebAppV4
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services // Web API routes
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"
);
}
}
}

首先是:using System.Net.Http.Formatting; 其实就是System.Net.Http.Formatting.dll。

然后是:config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
            config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml"
);

JsonMediaTypeFormatter和XmlMediaTypeFormatter是两个起实际作用的Media格式化器,用于序列化和反序列化HTTP请求及响应,给它们添加了$format参数之后就大功告成了!

这样,无论是在IE中,还是在chrome中,只要在url后面添加$format=json或$format=xml参数,浏览器就可以返回相应格式的数据了,也不必改Http请求Header中的Accept媒体类型了,这样测试WebAPI时更方便了。

URL如下:

http://localhost:port/api/ProjectManagent?$format=json

http://localhost:port/api/ProjectManagent?$format=xml

Demo源代码下载: 原代码下载

参考资料:https://code.msdn.microsoft.com/Support-format-in-ASPNET-e3785b2a

最新文章

  1. [Machine Learning] logistic函数和softmax函数
  2. 《Spark 官方文档》机器学习库(MLlib)指南
  3. CAN总线(一)
  4. 在cocos2dx和unity3d之间选择
  5. linux kernel i2c底层代码跟踪
  6. linux常用命令 2
  7. app启动其他应用
  8. library cache lock
  9. 51单片机C语言学习笔记8:单片机C51编程规范
  10. Java学习系列(一)Java的运行机制、JDK的安装配置及常用命令详解
  11. nodejs在服务器上运行
  12. nodejs显现events.js:72抛出错误
  13. openvpn实现内网 映射到 外网
  14. DesignModeler GestureRecgin…
  15. MyOD-Linux od命令的实现
  16. 快递单号自动识别接口API-trackingmore
  17. spring-mvc.xml与spring-mybatis.xml配置文件中命名空间问题
  18. MVC001之mvcpager简单分页
  19. (转)调优 DB2 UDB v8.1 及其数据库的最佳实践
  20. code1214 线段覆盖

热门文章

  1. 论maven release的必要性
  2. vue 解决双向绑定中 父组件传值给子组件后 父组件值也跟着变化的问题
  3. 浅谈CSS和JQuery实现鼠标悬浮图片放大效果
  4. hibernate中多对一问题
  5. 码云 使用 汉化 GitHub
  6. [BZOJ2650]积木
  7. 用spring boot 2从零开始创建区块链
  8. 枚举进程句柄File,Section,Mutant,Timer关闭Mutex句柄实现游戏多开
  9. .NetCore中EFCore for MySql整理(三)之Pomelo.EntityFrameworkCore.MySql
  10. .Net Core AES加密解密