在RestFul风格盛行的年代,对接接口大多数人会选择使用JSON,XML和JSON的对比传送(),看看这位博主是怎么说的,虽然最后没有说完,我想大概也能略微解决心中的疑惑。

1.其实要想让WebAPI 返回JSON格式的数据很简单,只要在ConfigureWebapi方法中配置一下即可。此前需要引用两个命名空间。

using Newtonsoft.Json.Serialization;using System.Linq;

2.核心代码如下:

var json = config.Formatters.JsonFormatter;// 解决json序列化时的循环引用问题json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器config.Formatters.Remove(config.Formatters.XmlFormatter);//设置序列化方式为驼峰命名法var jsonFormatter = config.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//  Web API 路由config.MapHttpAttributeRoutes();

完整代码如下:

        /// <summary>/// 配置WebApi/// </summary>/// <param name="app"></param>public void ConfigureWebapi(IAppBuilder app)        {//创建一个HTTP的实例配置var config = new HttpConfiguration();var json = config.Formatters.JsonFormatter;// 解决json序列化时的循环引用问题json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器            config.Formatters.Remove(config.Formatters.XmlFormatter);//设置序列化方式为驼峰命名法var jsonFormatter = config.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().First();            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//  Web API 路由            config.MapHttpAttributeRoutes();//映射路由            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );//将配置注入OWIN管道中            app.UseWebApi(config);        }

3.接下来让我们来测试一下,添加一个名为ProductController的Controller,删掉所有的方法,添加一个GetProductList方法,代码如下:

       [HttpGet]public HttpResponseMessage GetProduct()        {var product = new { id = 1, name = "三星王炸" };            HttpResponseMessage result = new HttpResponseMessage();            result.Content = new StringContent(JsonConvert.SerializeObject(product), Encoding.GetEncoding("UTF-8"), "application/json");return result;        }

4.在浏览器中输入http://localhost:27650/api/product/GetProduct ,输出结果为

image

5.我们发现如果在浏览器中输入http://localhost:27650/api/product 同样也可以获得返回值,让我们来简单改造一下重新再写一个新方法

        [HttpGet]public HttpResponseMessage GetProduct2(string id)        {var product = new { id = id, name = "三星王炸" };            HttpResponseMessage result = new HttpResponseMessage();            result.Content = new StringContent(JsonConvert.SerializeObject(product), Encoding.GetEncoding("UTF-8"), "application/json");return result;        }

6.在浏览器中输入http://localhost:27650/api/product?id=3 和 http://localhost:27650/api/product 得到的结果分别为

imageimage

为什么会出现这种现象呢,大家看看我们开始在配置WebAPI的路由规则,规则是api/{controller}/{id} ,也就是说此规则不会去匹配action的名称,而是根据传入的参数类型和个数来决定的。

image

7.那么如何让WebAPI 根据方法名称来匹配呢,让我们来修改一下路由规则,代码如下:

config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{action}/{id}",                defaults: new { id = RouteParameter.Optional }            );

8.让我们再测试一下,浏览器中输入http://localhost:27650/api/product,看一下效果。

image

再输入http://localhost:27650/api/product/GetProduct 和 http://localhost:27650/api/product/GetProduct?id=5,发现两个返回的结果一样,说明访问的是同一个方法。

imageimage

再输入http://localhost:27650/api/product/GetProduct2 和 http://localhost:27650/api/product/GetProduct2?id=6

结果:

image

image

测试通过。

这里仅作整理,加深印象,以防自己忘记。如有不正确的地方,欢迎不吝指教。

更多相关文章

  1. C#中方向键与回车键切换控件焦点的两种方法
  2. type=file的change事件只能执行一次的问题及解决方法实例
  3. 克隆对象的方法实例教程
  4. C# 中GUID生成格式有哪些方法
  5. 关于C#winform如何实现右下角弹出窗口结果的方法分享
  6. C#中如何格式化json字符串的方法分析
  7. C#中关于扩展方法的实例分析
  8. Asp.net MVC 对输入的字符串字段做Trim处理的方法_实用技巧
  9. Asp.net MVC 对用户输入的字符串做Trim处理的方法实例

随机推荐

  1. 教你怎么配置Android的AndroidManifest.x
  2. android4.2上获取应用程序大小的变更点
  3. Android Widget程序源码
  4. Gradle sync failed: Gradle DSL method
  5. 用于做 Android 屏幕自适应的文章资源
  6. Android程序设置成横屏方法
  7. Android 从uri中获取路径
  8. Android隐藏输入法软键盘的注意事项
  9. Android Softap启动分析
  10. Grade 编译 Android 解决 Error:more tha