好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

ASP.NET Web APIGET和POST数据

ASP.NET Web APIGET和POST数据

ASP.NET Web API(一):使用初探,GET和POST数据 Posted on  2012-09-27 11:59   Parry  阅读(480) 评论( 3 )  编辑   收藏  

概述

REST(Representational State Transfer表述性状态转移)而产生的REST API的讨论越来越多,微软在ASP.NET中也添加了Web API的功能。

我们看dudu的文章 HttpClient + ASP.NET Web API, WCF之外的另一个选择 知道了博客园也开始使用了Web API,且在使用Web API Beta版本的时候遇到了这个问题: 痴情意外:ASP.NET WebAPI RC 竟然不支持最常用的json传参 。

我们刚好看看Web API的使用,且看目前的版本有没有解决掉这个问题。

而关于ASP.NET Web Forms 4.5的新特性可以参见我之前的文章:

ASP.NET Web Forms 4.5的新特性(一):强类型数据控件和Bundling ASP.NET Web Forms 4.5的新特性(二):针对HTML5的更新和Unobtrusive Validation ASP.NET Web Forms 4.5的新特性(三):Model Binding

项目建立

在安装了Visual Studio 2012后,我们依次点击新建项目->已安装模板->Web->ASP.NET MVC 4 Web Application新建一个工程项目。

项目模板选择Web API。

在Model里面我们还是添加之前文章里面使用的User类。

 1   namespace  WebAPI.Models
 2  {
 3       public   class  Users
 4      {
 5           public   int  UserID {  get ;  set ; }
 6  
 7           public   string  UserName {  get ;  set ; }
 8  
 9           public   string  UserEmail {  get ;  set ; }
10      }
11  }

将自动生成的ValueController修改成UsersController。

GET数据

使用HTTP的get方法请求获取数据,整个Web API的请求处理基于MVC框架。

代码如下。

 1   using  System;
 2   using  System.Collections.Generic;
 3   using  System.Linq;
 4   using  System.Net;
 5   using  System.Net.Http;
 6   using  System.Web.Http;
 7   using  WebAPI.Models;
 8  
 9   namespace  WebAPI.Controllers
10  {
11       public   class  UsersController : ApiController
12      {
13           ///   <summary>
14            ///  User Data List
15            ///   </summary>
16           private   readonly  List<Users> _userList =  new  List<Users>
17          {
18               new  Users {UserID =  1 , UserName =  " Superman " , UserEmail =  " Superman@cnblogs.com " },
19               new  Users {UserID =  2 , UserName =  " Spiderman " , UserEmail =  " Spiderman@cnblogs.com " },
20               new  Users {UserID =  3 , UserName =  " Batman " , UserEmail =  " Batman@cnblogs.com " }
21          };
22  
23           //  GET api/Users
24           public  IEnumerable<Users> Get()
25          {
26               return  _userList;
27          }
28  
29           //  GET api/Users/5
30           public  Users GetUserByID( int  id)
31          {
32               var  user = _userList.FirstOrDefault(users => users.UserID == id);
33               if  (user ==  null )
34              {
35                   throw   new  HttpResponseException(HttpStatusCode.NotFound);
36              }
37               return  user;
38          }
39  
40           // GET api/Users/?username=xx
41           public  IEnumerable<Users> GetUserByName( string  userName)
42          {
43               return  _userList.Where(p =>  string .Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase));
44          }
45      }
46  }

构造了一个user list,实现了三个方法,我们下面来做请求。

使用不同的浏览器请求的过程中会发现返回的格式不一样。

先使用Chrome请求,我们发现HTTP Header里面的Content-Type是xml类型。

我们再换FireFox请求,发现Content-Type还是xml类型。

我们再使用IE请求,发现是这样。

打开保存后的文件,我们发现请求到的数据是JSON格式。

造成这样的差异的原因是:不同的浏览器发送的Request Header里面的Content-Type不一致造成的。

我们可以使用 Fiddler 验证一下。

Content-Type:text/json

Content-Type:text/xml

POST数据

实现一个User添加的功能,接受的类型为User实体,而我们POST的数据为对应的JSON数据,看看dudu在Beta版本的遇到的问题有没有解决。

 1   // POST api/Users/Users Entity Json
 2   public  Users Add([FromBody]Users users)
 3  {
 4       if  (users ==  null )
 5      {
 6           throw   new  HttpRequestException();
 7      }
 8      _userList.Add(users);
 9       return  users;
10  }

我们还是使用Fiddler进行模拟POST数据。

在POST请求前,我们先将代码附加到进程里面,并在Add方法处设置断点。

在Visual Studio 2012中,debug HOST的程序变成了IIS Express。

我们使用Ctrl+ALT+P,附加到它的进程里面。

下面使用Fiddler进行模拟POST。

注意在Request Header里面的Content-Type为text/json,POST的json内容为:

1  {"UserID":4,"UserName":"Parry","UserEmail": Parry@cnblogs.com }

点击Execute后,跳到了我们前面设置的断点处,我们看看提交过来的数据。

这样dudu在Beta里面遇到的问题已解。

结语

ASP.NET框架一路发展而来,的确功能做的越来越强大、方便。希望我们能摒弃语言的争论,回归纯粹的技术讨论上来,都说微软的技术变化太快,变的本质是什么呢?难道不变就是好的吗?

第二部分我们将一起看一看Web API里面的一些安全验证的问题。

有所错误之处,望指出、讨论。

喜欢的话,点个支持是对文章最好的肯定。 :)

DEMO源码下载


作者: Parry  
出处: http://www.cnblogs.com/parry/  
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

分类:  00.ASP.NET

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于ASP.NET Web APIGET和POST数据的详细内容...

  阅读:54次