如何使用 Web API 来对 MVC 应用程序进行mvc web api身份验证证

如何使用 Web API 来对 MVC 应用程序进行身份验证_百度知道
如何使用 Web API 来对 MVC 应用程序进行身份验证
&[BasicAuthentication]public abstract class ApiControllerB.Config配置[html] view plaincopy&lt, Culture=SPAN&compilation&gt,用于实现适合业务场景的基础功能/ /id3 not found&SSPAN&&&AES&quot.Wassemblies&&forms loginUrl=&如果请求Header不包含&#47.&}else{compilation debug=&quot.OnActionExecuting(actionContext);}}4.ActionD });/&add assembly=&&#47.Any(a =&/var isQuilified = CheckUser(userN}bool isAnonymous =&/SPAN&5[HttpGet][AllowAnonymous]public Product Get(string id){var headers = RSPAN&gt.Rif (isRquired){&#47.R//&#47.0: ApiController{}2 权限属性BaseAuthenticationAttribute[csharp] view plaincopy// validation=&elseactionC~/非匿名用户.web&/&&&lt,抛出“未授权访问”信息if (isAnonymous)base.web&&lt.Response = new HttpResponseMessage(HttpStatusCode。2);system.Unauthorized);public class BasicAuthenticationAprivate bool ValidateUserTicket(string encryptTicket){var userTicket = FormsA/&#47,用户ticket信息来自调用发起方if (actionC/解密用户ticket.Parse(id));SPAN&/ &#47,则继续执行;4;Forms&forms&//&#47:&&lt.Substring(userTicketData.config配置是否要求权限校验bool isRquired = (WebConfigurationM/Account/&SPAN&gt.IndexOf(&SPAN&/&&}/&/& protection=&&#47,并校验用户名密码是否匹配var encryptTicket = actionC&#47,用以Action的权限处理/&lt,是应用于对用户ticket数据加密和解密.GetById(检查用户名;SHA1&quot、WebApi服务端Web, Version=4;/true&var userTicketData = userTicket、密码是否正确.web&Index&quot.H& &#47、 Mvc前端W&string userName = userTicketDmachineKey validationKey=&quot.P defaultUrl=&quot.A decryptionKey=&&string password = userTicketData.BadRequest)Content = new StringContent(&quot.GetCustomAttributes();3FFA12388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE908D193A17C1FC8DCE51B71A4AE54920&;All&&lt:& targetFramework=&));/&authentication&/SPAN&/if (p == null){throw new HttpResponseException(new HttpResponseMessage(HttpStatusC //&// decryptionKey=&SHA1&quot.OnActionExecuting(actionContext);elseactionC&lt.Find(2);&#47.H&product&#47.0.Authorization , ReasonPhrase = &/var p = ProductServiceI/&}}}/);&#47.Unauthorized);SPAN&gt.5&&WebApiAuthenticatedFlag&/SPAN& validation=&;&SPAN&SPAN& Controller的基类;//&&#47, PublicKeyToken=31bf&ECB6A3AF9ABBF3F16E8B0B13CCEE538EBBA97D0BB&90&Home/&/ timeout=&SPAN&gt.Substring(0;3FF112388DDF585BA5D35E7BC87E3F0AB47FBBEBD12240DD3BEA2BEAEC4ABA213F22AD27E8FAD77DCFEE908D193A17C1FC8DCE51B71A4AE54920& 检查用户是否有该Action执行的操作权限/SPAN&/authentication mode=&&&lt.OnActionExecuting(actionContext), password);//SPAN&&#47.5&&#47,验证是合法用户/4;/); name=&quot: ApiControllerBase{[HttpGet]public object Find(string id){return ProductServiceI&/&}else{/ GET api//&/SPAN&&#47.web&public override void OnActionExecuting(HttpActionContext actionContext){/ decryption=&是匿名用户;/) + 1).D//&#47.Response = new HttpResponseMessage(HttpStatusCmachineKey节点配置;/ a is AllowAnonymousAttribute).Config 配置[html] view plaincopy&lt.IndexOf(&quot.Headers. 其它配置说明1);检查product id not exist.AuthCookie&quot.AppSettings[&/machineKey validationKey=&/&}}3 api服务Controller实例[csharp] view plaincopypublic class ProductController , userTicketDmachineKey节点配置.0;true&quot.H/&#47!= null){/ECB6A3AF9ABBF3F16E8B0B13CCEE538EBBA97D0BB&/AES&quot.OfType();];////&#47.UserD/if (ValidateUserTicket(encryptTicket))~//&#47: ActionFilterAttribute{///httpRuntime targetFramework=&& 基本验证Attribtue.Decrypt(encryptTicket);Login&quot.ToString() == &&#47,是应用于对用户ticket数据加密和解密;assemblies&gt,则判断是否是匿名调用var attr = actionC检验用户ticket信息.H/ 校验用户ticket信息/ decryption=&/&#471 控制器基类ApiControllerBase[csharp] view plaincopy&#47
网络管理与维护
其他类似问题
为您推荐:
其他2条回答
  如果你的Web API运行在IIS中:在宿主程序中的身份验证和使用 HTTP Message Handlers进行身份验证,如果用户验证通过,参见Role-Based Security。principal包含一个关联用户信息的Identity 对象。  当在宿主程序中进行身份验证时.IsAuthenticated 属性返回true.CurrentPrincipal 将主体附加到当前进程,可以使用内置的asp,这个对象的类实现了IPrincipal接口,用来代表当前代码运行的安全上下文,那么身份验证程序就是HTTP Modules。关于更多的principals信息,Identity,也可以自己写一个身份验证模块完成自定义身份验证,IsAuthenticated 返回false.net身份验证模块进行身份验证,宿主程序会创建一个principal对象;对于匿名请求。宿主通过设置Thread  Web API有两种方式进行身份验证
Yii框架 Yii是一个基于组件、用于开发大型 Web 应用的 高性能 PHP 框架。Yii 几乎拥有了 所有的特性 ,包括 MVC、DAO/ActiveRecord、I18N/L10N、caching、基于 JQuery 的 AJAX 支持、用户认证和基于角色的访问控制、脚手架、输入验证、部件
mvc的相关知识
等待您来回答
下载知道APP
随时随地咨询
出门在外也不愁其他回答(2)
可以看一下园子里的这篇博文:
园豆:36185
分布式框架,你不用的话可以不用理
&&&您需要以后才能回答,未注册用户请先。ASP.Net MVC开发基础学习笔记(5):区域、模板页与WebAPI初步 - 文章 - 伯乐在线
& ASP.Net MVC开发基础学习笔记(5):区域、模板页与WebAPI初步
一、区域—麻雀虽小,五脏俱全的迷你MVC项目
1.1 Area的兴起
为了方便大规模网站中的管理大量文件,在ASP.NET MVC 2.0版本中引入了一个新概念—区域(Area)。
在项目上右击创建新的区域,可以让我们的项目不至于太复杂而导致管理混乱。有了区域后,每个模块的页面都放入相应的区域内进行管理很方便。例如:上图中有两个模块,一个是Admin模块,另一个是Product模块,所有关于这两个模块的控制器、Model以及视图都放入各自的模块内。可以从上图中看出,区域的功能类似一个小的MVC项目,麻雀虽小五脏俱全,有自己的控制器、模型、视图还有路由设置。
区域实际上是应用程序内部的一个 MVC 结构,一个应用程序可能包含若干个 MVC 结构(区域)。例如:一个大型电子商务应用程序可能分为若干个区域,这些区域表示店面、产品检查、用户帐户管理和采购系统。每个区域表示整个应用程序的一个独立功能。
1.2 注册区域路由
在MVC中添加一个Area区域之后,会默认帮我们注册这个区域的路由规则。例如:我们创建了一个Admin的区域,然后它帮我们生成了一个AdminAreaRegistration.cs的文件,其代码如下:
public class AdminAreaRegistration : AreaRegistration
public override string AreaName
return "Admin";
public override void RegisterArea(AreaRegistrationContext context)
context.MapRoute(
"Admin_default",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
12345678910111213141516171819
public class AdminAreaRegistration : AreaRegistration{&&&&&&&&public override string AreaName&&&&&&&&{&&&&&&&&&&&&get&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return "Admin";&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&&public override void RegisterArea(AreaRegistrationContext context)&&&&&&&&{&&&&&&&&&&&&context.MapRoute(&&&&&&&&&&&&&&&&"Admin_default",&&&&&&&&&&&&&&&&"Admin/{controller}/{action}/{id}",&&&&&&&&&&&&&&&&new { action = "Index", id = UrlParameter.Optional }&&&&&&&&&&&&);&&&&&&&&}}
这里,RegisterArea是实现注册的关键方法,通过把另一个路由添加到区域路由集合中实现。请注意,这里的区域名Admin是以硬编码方式添加到URL中;因此,所有使用此区域名称作为前缀的请求都被进行特别路由处理。
你可能感到疑惑:为什么我们不能在主应用程序的路由定义中指定Admin部分?实际上,如果我们将它加入到标准的路由表中,而不通过区域上下文(AreaRegistrationContext),那么我们还是把所有文件驻留到同一个项目中,从而失去了分离项目区域的好处(即区域没有起到作用)。
二、模板页—封装页面变化点,构建快速View开发模板
在传统的WebForm开发模式中,我们使用MasterPage作为模板页。那么在MVC3 Razor视图设计中,我们怎么来使用模板页呢?
2.1 模板页的归宿—Shared文件夹
在解决方案资源管理中,我们可以看到Views文件夹下面有一个Shared文件夹。在Shared文件夹里面有一个_Layout.cshtml页面。这个就是项目中默认的模板页面,如下图所示:
在Shared中新建一个MVC布局页,取名为:_MyLayout.cshtml
&!DOCTYPE html&
&meta name="viewport" content="width=device-width" /&
&title&@ViewBag.Title&/title&
@RenderSection("Head", required: false)
&h1&This is MyLayout Page&/h1&
@RenderBody()
123456789101112131415
&!DOCTYPE html&&html&&head&&&&&&meta name="viewport" content="width=device-width" /&&&&&&title&@ViewBag.Title&/title&&/head&&body&&&&&&div&&&&&&&&&@RenderSection("Head", required: false)&&&&&&&&&h1&This is MyLayout Page&/h1&&&&&&&&&&hr /&&&&&&&&&@RenderBody()&&&&&/div&&/body&&/html&
其中RenderSection为渲染指定区域,该区域名称为Head,但不是必须渲染(required:false)。而RenderBody则是重头戏,他就类似于MasterPage中主内容的PlaceHolder,是每个使用该模板页都需填充的内容区域。
那么,怎么来使用这个模板页呢?其实很简单,只需要在要使用模板页的View中修改Layout属性即可:
2.2 View未动,ViewStart先行
在Razor视图引擎中,所有页面启动之前,ViewStart文件会先执行。那么,这个ViewStart文件到底做了些什么事儿呢?
(1)可以看出,这个ViewStart是一个全局的页面。当我们的页面未指定Layout的时候,如果项目在全局或在同文件夹内存在_ViewStart.cshtml时该页面的Layout会自动继承自_ViewStart.cshtml,如果不同的文件夹层级都存在_ViewStart.cshtml,则继承离该页面最近的一个。
(2)如果我们想要所有的页面都默认使用一个指定模板页,只需将这个Layout改为新模板页即可。例如:将Layout改为我们刚刚创建的~/Views/Shared/_MyLayout.cshtml。
2.3 RenderBody与RenderSection
(1)RenderBody:
@RenderBody()在模板页中使用表示内容页在模板中的位置。当创建具有模板页的内容页的时候,内容页就呈现在模板页中@RenderBody()所在的位置,一个模板页中只能有一个@RenderBody()。
(2)RenderSection:
@RenderSection用于在模板布局中定义一个区域,在内容页可以定义一些内容来填充这个区域,例如内容页中引用的JS文件,可以填充到模板页的section位置。每个内容页的单独一些信息,可以在模板页中这个区域显示。
@RenderSection有两个个参数,第一个参数用于定义section的名称,第2个参数是布尔类型,如果为TRUE,表示内容页必须定义这个section,如果为false,则表示内容页可定义section,也可以不定义。
三、WebAPI初步—构建轻量级Restful服务的利器
3.1 Restful架构是什么?
RESTful架构,就是目前最流行的一种互联网软件架构。它结构清晰、符合标准、易于理解、扩展方便,所以正得到越来越多网站的采用。
这里借用阮一峰博士的总结,到底什么是Restful架构:
(1)每一个URI代表一种资源;
(2)客户端和服务器之间,传递这种资源的某种表现层;
(3)客户端通过四个HTTP动词,对服务器端资源进行操作,实现”表现层状态转化“。
各位园友可以阅读阮一峰博士的这篇《》的文章来了解Restful架构的基本概念。
综上所示,REST是一种简洁的设计风格,通过URL来设计系统,以URI来抽象各种资源,以HTTP协议的PUT、DELETE、GET、POST来对应对资源的各种操作。
3.2 WCF and WebAPI
首先,ASP.NET Web API 和WCF有着千丝万缕的联系。
WCF是一个通用的服务架构平台,其设计之初在于创建一个通用的Web Service平台,可以在各种不同的协议(TCP, UDP, HTTP)下使用,仅仅通过EndPoint的配置而不需要修改代码实现就能适应不同的工作环境。WCF也是微软以前很多服务产品的合体。
WCF 里面可以采用模板的方式来实现REST架构风格,但WCF毕竟是一个集大成的平台(或者说是:比较重量级)。WCF的野心造成了它的庞大复杂,HTTP的单纯造就了它的简单优美。于是经常自问:拿着牛刀削苹果有必要吗?废话,当然没有必要,水果刀在哪里?因此,我们所需要的仅仅是里面HTTP REST风格的部分。各种因素纠结下,微软于是便把WCF里面的这部分团队抽离出来合并到了MVC组中,才有了现在的ASP.NET Web API,并包含在MVC 4中发布。
3.3 第一个WebAPI项目
(1)新建一个ASP.NET MVC项目,取名为:MyMvcWebAPIDemo,项目类型选择WebAPI。
(2)在Models中新增一个类,取名为:Product,作为我们要测试的实体模型。
public class Product
public int Id { }
public string Name { }
public string Category { }
public decimal Price { }
public class Product&&&&{&&&&&&&&public int Id { get; set; }&&&&&&&&public string Name { get; set; }&&&&&&&&public string Category { get; set; }&&&&&&&&public decimal Price { get; set; }&&&&}
(3)在Controllers中新增一个控制器,并选择“空WebAPI”类型模板,取名为:ProductController。
(4)为了方便进行数据测试,这里定义一个静态的产品集合。当然,在实际应用中,我们可能会从数据库中读取数据集合,并对其进行增删查改及各种查询操作。
static List&Product& products = new List&Product&
new Product { Id = 1, Name = "Nokia Lumia 1520", Category = "移动电话", Price = 3500 },
new Product { Id = 2, Name = "Lenovo Thinkpad T430S", Category = "便携式计算机", Price = 8000 },
new Product { Id = 3, Name = "锤子手机", Category = "移动电话", Price = 3300 } ,
new Product { Id = 4, Name = "Wii", Category = "电视游戏机", Price = 1000 },
new Product { Id = 5, Name = "Xbox 360", Category = "电视游戏机", Price = 3200 }
static List&Product& products = new List&Product& &&&&&&&&{ &&&&&&&&&&&&new Product { Id = 1, Name = "Nokia Lumia 1520", Category = "移动电话", Price = 3500 }, &&&&&&&&&&&&new Product { Id = 2, Name = "Lenovo Thinkpad T430S", Category = "便携式计算机", Price = 8000 }, &&&&&&&&&&&&new Product { Id = 3, Name = "锤子手机", Category = "移动电话", Price = 3300 } ,&&&&&&&&&&&&new Product { Id = 4, Name = "Wii", Category = "电视游戏机", Price = 1000 },&&&&&&&&&&&&new Product { Id = 5, Name = "Xbox 360", Category = "电视游戏机", Price = 3200 } &&&&&&&&};
(5)定义一些方法,用于对产品集合的各种操作:
public class ProductController : ApiController
static List&Product& products = new List&Product&
new Product { Id = 1, Name = "Nokia Lumia 1520", Category = "移动电话", Price = 3500 },
new Product { Id = 2, Name = "Lenovo Thinkpad T430S", Category = "便携式计算机", Price = 8000 },
new Product { Id = 3, Name = "锤子手机", Category = "移动电话", Price = 3300 } ,
new Product { Id = 4, Name = "Wii", Category = "电视游戏机", Price = 1000 },
new Product { Id = 5, Name = "Xbox 360", Category = "电视游戏机", Price = 3200 }
/// &summary&
/// &/summary&
/// &returns&&/returns&
public IEnumerable&Product& GetAllProducts()
return products.OrderBy(p =& p.Id);
/// &summary&
/// &/summary&
/// &param name="id"&&/param&
/// &returns&&/returns&
public Product GetProductById(int id)
Product product = products.FirstOrDefault(p =& p.Id == id);
if (product == null)
var resp = new HttpResponseMessage(HttpStatusCode.NotFound);
throw new HttpResponseException(resp);
/// &summary&
/// &/summary&
/// &param name="productName"&产品名&/param&
/// &returns&&/returns&
public Product GetProductByName(string productName)
Product product = products.FirstOrDefault(p =& p.Name.Contains(productName));
if (product == null)
var resp = new HttpResponseMessage(HttpStatusCode.NotFound);
throw new HttpResponseException(resp);
/// &summary&
/// &/summary&
/// &param name="category"&类型名称&/param&
/// &returns&&/returns&
public IEnumerable&Product& GetAllProductsByCategory(string category)
if (category.Equals("--请选择--"))
IEnumerable&Product& productList = products.Where(
p =& string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
return productList.OrderBy(p =& p.Id);
/// &summary&
/// &/summary&
/// &returns&&/returns&
public bool PostProduct(Product product)
int index = products.FindIndex(p =& p.Name == product.Name);
if (index != -1)
product.Id = products.Max(p =& p.Id) + 1;
products.Add(product);
/// &summary&
/// &/summary&
/// &returns&&/returns&
public bool PutProduct(int id, [FromBody]Product product)
int index = products.FindIndex(p =& p.Id == id);
if (index == -1)
products.RemoveAt(index);
products.Add(product);
/// &summary&
/// DELETE
/// &/summary&
/// &returns&&/returns&
public bool DeleteProduct(int id)
Product product = products.FirstOrDefault(p =& p.Id == id);
if (product == null)
products.Remove(product);
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
public class ProductController : ApiController&&&&{&&&&&&&&static List&Product& products = new List&Product& &&&&&&&&{ &&&&&&&&&&&&new Product { Id = 1, Name = "Nokia Lumia 1520", Category = "移动电话", Price = 3500 }, &&&&&&&&&&&&new Product { Id = 2, Name = "Lenovo Thinkpad T430S", Category = "便携式计算机", Price = 8000 }, &&&&&&&&&&&&new Product { Id = 3, Name = "锤子手机", Category = "移动电话", Price = 3300 } ,&&&&&&&&&&&&new Product { Id = 4, Name = "Wii", Category = "电视游戏机", Price = 1000 },&&&&&&&&&&&&new Product { Id = 5, Name = "Xbox 360", Category = "电视游戏机", Price = 3200 } &&&&&&&&};&&&&&&&&&/// &summary&&&&&&&&&/// GET&&&&&&&&/// &/summary&&&&&&&&&/// &returns&&/returns&&&&&&&&&public IEnumerable&Product& GetAllProducts()&&&&&&&&{&&&&&&&&&&&&return products.OrderBy(p =& p.Id);&&&&&&&&}&&&&&&&&&/// &summary&&&&&&&&&/// GET&&&&&&&&/// &/summary&&&&&&&&&/// &param name="id"&&/param&&&&&&&&&/// &returns&&/returns&&&&&&&&&public Product GetProductById(int id)&&&&&&&&{&&&&&&&&&&&&Product product = products.FirstOrDefault(p =& p.Id == id);&&&&&&&&&&&&if (product == null)&&&&&&&&&&&&{&&&&&&&&&&&&&&&&var resp = new HttpResponseMessage(HttpStatusCode.NotFound);&&&&&&&&&&&&&&&&throw new HttpResponseException(resp);&&&&&&&&&&&&}&&&&&&&&&&&&&return product;&&&&&&&&}&&&&&&&&&/// &summary&&&&&&&&&/// GET&&&&&&&&/// &/summary&&&&&&&&&/// &param name="productName"&产品名&/param&&&&&&&&&/// &returns&&/returns&&&&&&&&&public Product GetProductByName(string productName)&&&&&&&&{&&&&&&&&&&&&Product product = products.FirstOrDefault(p =& p.Name.Contains(productName));&&&&&&&&&&&&if (product == null)&&&&&&&&&&&&{&&&&&&&&&&&&&&&&var resp = new HttpResponseMessage(HttpStatusCode.NotFound);&&&&&&&&&&&&&&&&throw new HttpResponseException(resp);&&&&&&&&&&&&}&&&&&&&&&&&&&return product;&&&&&&&&}&&&&&&&&&/// &summary&&&&&&&&&/// GET&&&&&&&&/// &/summary&&&&&&&&&/// &param name="category"&类型名称&/param&&&&&&&&&/// &returns&&/returns&&&&&&&&&public IEnumerable&Product& GetAllProductsByCategory(string category)&&&&&&&&{&&&&&&&&&&&&if (category.Equals("--请选择--"))&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return products;&&&&&&&&&&&&}&&&&&&&&&&&&&IEnumerable&Product& productList = products.Where(&&&&&&&&&&&&&&&&p =& string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));&&&&&&&&&&&&return productList.OrderBy(p =& p.Id);&&&&&&&&}&&&&&&&&&/// &summary&&&&&&&&&/// POST&&&&&&&&/// &/summary&&&&&&&&&/// &returns&&/returns&&&&&&&&&public bool PostProduct(Product product)&&&&&&&&{&&&&&&&&&&&&int index = products.FindIndex(p =& p.Name == product.Name);&&&&&&&&&&&&if (index != -1)&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return false;&&&&&&&&&&&&}&&&&&&&&&&&&product.Id = products.Max(p =& p.Id) + 1;&&&&&&&&&&&&products.Add(product);&&&&&&&&&&&&return true;&&&&&&&&}&&&&&&&&&/// &summary&&&&&&&&&/// PUT&&&&&&&&/// &/summary&&&&&&&&&/// &returns&&/returns&&&&&&&&&public bool PutProduct(int id, [FromBody]Product product)&&&&&&&&{&&&&&&&&&&&&int index = products.FindIndex(p =& p.Id == id);&&&&&&&&&&&&if (index == -1)&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return false;&&&&&&&&&&&&}&&&&&&&&&&&&&products.RemoveAt(index);&&&&&&&&&&&&products.Add(product);&&&&&&&&&&&&return true;&&&&&&&&}&&&&&&&&&/// &summary&&&&&&&&&/// DELETE&&&&&&&&/// &/summary&&&&&&&&&/// &returns&&/returns&&&&&&&&&public bool DeleteProduct(int id)&&&&&&&&{&&&&&&&&&&&&Product product = products.FirstOrDefault(p =& p.Id == id);&&&&&&&&&&&&if (product == null)&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return false;&&&&&&&&&&&&}&&&&&&&&&&&&&products.Remove(product);&&&&&&&&&&&&return true;&&&&&&&&}&&&&}
一般来说,Http的四种访问类型中,Get:一般用作查询,多次操作得到结果一致;Post:一般用于修改、添加多次重复操作得到结果不一致。Put:一般用于修改,多次操作得到结果一致。Delete:一般用于删除数据,多次操作得到结果一致。
现在,我们来看一下我们写的这些方法:
①用于GET方式获取的方法有:
GetAllProducts用于获取所有产品的集合;GetProductById用于返回指定Id的产品对象;
GetProductByName用户返回指定Name的产品对象;GetAllProductsByCategory则用户返回指定Category(种类)的产品集合;
②用于POST方式的方法有:
PostProduct用于增加一个产品信息;
③用于PUT方式的方法有:
PutProduct用于修改一个指定的产品信息;
④用于DELETE方式的方法有:
DeleteProduct用于删除一个选择的产品信息;
以上GET、POST、PUT、DELETE则构成了我们通过HTTP协议对资源的各种操作了。具体的代码,这里我就不过多赘述,相信大家都能看懂。
(6)此时,我们有了一个能工作的Web API了。该控制器上的每个方法都映射到一个URI,例如下表中所示的前三个方法所对应的URI:
Controller Method
控制器方法
GetAllProducts
/api/product
GetProductById
/api/product/id
GetProductsByCategory
/api/product/?category=category
客户端可以通过URI来访问我们的控制器已达到对资源的操作,那么,我们可以设计一个页面来发送AJAX请求来实践一下。
(7)在Views中的默认Home/Index这个页面中,加入以下代码:
&link href="~/Content/themes/easyui/bootstrap/easyui.css" rel="stylesheet" /&
&link href="~/Content/themes/easyui/icon.css" rel="stylesheet" /&
&div class="content-wrapper"&
&div class="float-left"&
&p class="site-title"&
&a href="~/"&ASP.NET Web API&/a&
&div id="body"&
&section class="featured"&
&div class="content-wrapper"&
@*&hgroup class="title"&
&h1&欢迎使用 ASP.NET Web API!&/h1&
&h2&这是一个简单的WebAPI入门Demo.&/h2&
&/hgroup&*@
&strong&搜索:&/strong&
①产品类型:
&select id="productTypes" name="productTypes" style="width: 120 height: 34"&
&option value="-1"&--请选择--&/option&
&option value="0"&移动电话&/option&
&option value="1"&便携式计算机&/option&
&option value="2"&电视游戏机&/option&
②产品名称:&input id="productName" name="productName" type="text" /&
&input id="btnSearchByName" name="btnSearchByName" type="button" value="搜 索" /&
&input id="btnSearchAll" name="searchAll" type="button" value="全 部" /&
&strong&新增:&/strong&
产品名称:&input id="newProductName" name="newProductName" type="text" /&
产品类型:&select id="newProductType" name="newProductType" style="width: 120 height: 34"&
&option value="-1"&--请选择--&/option&
&option value="0"&移动电话&/option&
&option value="1"&便携式计算机&/option&
&option value="2"&电视游戏机&/option&
产品价格:&input id="newProductPrice" name="newProductPrice" type="text" /&
&input id="btnPostProduct" name="btnPostProduct" type="button" value="新 增" /&
&/section&
&section class="content-wrapper main-content clear-fix"&
&h3&下面是从WebAPI获取的数据集:&/h3&
&div id="result"&
@*&ol class="round"&
&li class="one"&
&h5&开始使用&/h5&
ASP.NET Web API
是一个框架,您可以通过该框架轻松生成可访问
多种客户端(包括浏览器和移动设备)的 HTTP 服务。ASP.NET Web API
是一个用于在 .NET Framework 之上生成 REST 样式的应用程序的理想平台。
&a href="/fwlink/?LinkId=245160"&了解详细信息...&/a&
&/section&
&!-- jBox modal --&
&div id="myMsgModal" class="notshow"&
&!-- jBox edit modal --&
&div id="myEditModal" class="notshow"&
&input id="hiddProductId" type="hidden" /&
&table width="100%"&
&td align="right"&产品名称:&/td&
&input id="editProductName" name="editProductName" type="text" /&&/td&
&td align="right"&产品类型:&/td&
&select id="editProductType" name="editProductType" style="width: 120 height: 34"&
&option value="-1"&--请选择--&/option&
&option value="0"&移动电话&/option&
&option value="1"&便携式计算机&/option&
&option value="2"&电视游戏机&/option&
&td align="right"&产品价格:&/td&
&input id="editProductPrice" name="editProductPrice" type="text" /&
&td colspan="2" align="center"&
&a id="btnPutProduct" href="#" class="easyui-linkbutton"&确定&/a&
&a id="btnCloseModal" href="#" class="easyui-linkbutton"&关闭&/a&
@section scripts{
&script src="~/Scripts/jquery-1.7.1.min.js"&&/script&
&script src="~/Content/themes/easyui/jquery.easyui.min.js"&&/script&
&script src="~/Content/themes/easyui/easyui-lang-zh_CN.js"&&/script&
&script type="text/javascript"&
$(function () {
initData();
bindClick();
function initData() {
$.getJSON("api/Product", function (data) {
if (data != null) {
if ($("#resultList").length & 0) {
$("#resultList").remove();
var html = "&ol id='resultList' class='round'&";
$.each(data, function (key, value) {
html += "&li class='one'&&h5&" + value.Name + "&/h5&类型:" + value.Category
+ " 价格:" + value.Price + "
| &a href='#' onclick='editProduct(" + value.Id + ")'&编辑&/a&&a href='#' onclick='deleteProduct(" + value.Id + ")'&删除&/a&&/li&";
html += "&/ol&";
$("#result").append(html);
function bindClick() {
// 01.按产品类型搜索产品
$("#productTypes").bind("change", function () {
$.getJSON("api/Product", { category: $(this).find("option:selected").text() }, function (data) {
if (data != null) {
$("#resultList").remove();
var html = "&ol id='resultList' class='round'&";
$.each(data, function (key, value) {
html += "&li class='one'&&h5&" + value.Name + "&/h5&类型:" + value.Category
+ " 价格:" + value.Price + "
| &a href='#' onclick='editProduct(" + value.Id + ")'&编辑&/a&&a href='#' onclick='deleteProduct(" + value.Id + ")'&删除&/a&&/li&";
html += "&/ol&";
$("#result").append(html);
// 02.按产品名搜索产品
$("#btnSearchByName").bind("click", function () {
var searchName = $("#productName").val();
if (searchName == "") {
showMsg("提示", "您还没有输入要搜索的产品名称");
$.getJSON("api/Product", { productName: searchName }, function (data) {
if (data != null) {
$("#resultList").remove();
var html = "&ol id='resultList' class='round'&";
html += "&li class='one'&&h5&" + data.Name + "&/h5&类型:" + data.Category
+ " 价格:" + data.Price + "
| &a href='#' onclick='editProduct(" + data.Id + ")'&编辑&/a&&a href='#' onclick='deleteProduct(" + data.Id + ")'&删除&/a&&/li&";
html += "&/ol&";
$("#result").append(html);
clearText();
// 03.搜索全部产品信息
$("#btnSearchAll").bind("click", initData);
// 04.新增一个产品信息
$("#btnPostProduct").bind("click", function () {
var productName = $("#newProductName").val();
var productCategory = $("#newProductType").find("option:selected").text();
var productPrice = $("#newProductPrice").val();
if (productName == "") {
showMsg("提示", "请输入产品名称");
else if (productCategory == "" || productCategory == "--请选择--") {
showMsg("提示", "请选择产品类型");
else if (productPrice == "") {
showMsg("提示", "请输入产品价格");
else if (isNaN(productPrice)) {
showMsg("提示", "产品价格请输入数字类型");
$.post("api/Product", {
Name: productName,
Category: productCategory,
Price: productPrice
}, function (data) {
if (data != null && data == true) {
initData();
clearText();
showMsg("提示", "添加新产品操作成功");
showMsg("提示", "添加新产品操作失败");
// 07.修改一个产品信息
$("#btnPutProduct").bind("click", function () {
var productId = $("#hiddProductId").val();
type: "PUT",
url: "/api/Product/" + productId,
Id: productId,
Name: $("#editProductName").val(),
Category: $("#editProductType").find("option:selected").text(),
Price: $("#editProductPrice").val()
success: function (data) {
if (data == true) {
initData();
$("#myEditModal").window("close");
showMsg("提示", "您已成功修改那玩意");
showMsg("提示", "修改那玩意操作失败");
// 关闭模态对话框
$("#btnCloseModal").bind("click", function () {
$("#myEditModal").window("close");
// 05.编辑一个产品信息
function editProduct(productId) {
$.getJSON("api/Product", { id: productId }, function (data) {
if (data != null) {
$("#hiddProductId").val(data.Id);
$("#editProductName").val(data.Name);
switch (data.Category) {
case "移动电话":
$("#editProductType").val("0");
case "便携式计算机":
$("#editProductType").val("1");
case "电视游戏机":
$("#editProductType").val("2");
$("#editProductPrice").val(data.Price);
$("#myEditModal").show();
$("#myEditModal").window({
title: "编辑产品信息",
modal: true,
collapsible: true,
minimizable: false,
maximizable: false,
resizable: false,
width: 500,
height: 220
// 06.删除一个产品信息
function deleteProduct(productId) {
$.messager.confirm("提示", "您确定要删除这玩意?", function (r) {
type: "DELETE",
url: "/api/Product/" + productId,
success: function (data) {
if (data == true) {
initData();
showMsg("提示", "您已成功删除那玩意");
showMsg("提示", "删除那玩意操作失败");
function showMsg(title, msg) {
$.messager.alert(title, msg, "info");
function clearText() {
$("input[type=text]").val("");
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
&link href="~/Content/themes/easyui/bootstrap/easyui.css" rel="stylesheet" /&&link href="~/Content/themes/easyui/icon.css" rel="stylesheet" /&&header&&&&&&div class="content-wrapper"&&&&&&&&&&div class="float-left"&&&&&&&&&&&&&&p class="site-title"&&&&&&&&&&&&&&&&&&a href="~/"&ASP.NET Web API&/a&&&&&&&&&&&&&&/p&&&&&&&&&&/div&&&&&&/div&&/header&&div id="body"&&&&&&section class="featured"&&&&&&&&&&div class="content-wrapper"&&&&&&&&&&&&&@*&hgroup class="title"&&&&&&&&&&&&&&&&&&h1&欢迎使用 ASP.NET Web API!&/h1&&&&&&&&&&&&&&&&&&h2&这是一个简单的WebAPI入门Demo.&/h2&&&&&&&&&&&&&&/hgroup&*@&&&&&&&&&&&&&p&&&&&&&&&&&&&&&&&&strong&搜索:&/strong&&&&&&&&&&&&&&&&&①产品类型:&&&&&&&&&&&&&&&&&&&&&select id="productTypes" name="productTypes" style="width: 120 height: 34"&&&&&&&&&&&&&&&&&&&&&&&&&&option value="-1"&--请选择--&/option&&&&&&&&&&&&&&&&&&&&&&&&&&option value="0"&移动电话&/option&&&&&&&&&&&&&&&&&&&&&&&&&&option value="1"&便携式计算机&/option&&&&&&&&&&&&&&&&&&&&&&&&&&option value="2"&电视游戏机&/option&&&&&&&&&&&&&&&&&&&&&&/select&&&&&&&&&&&&&&&&&②产品名称:&input id="productName" name="productName" type="text" /&&&&&&&&&&&&&&&&&&input id="btnSearchByName" name="btnSearchByName" type="button" value="搜 索" /&&&&&&&&&&&&&&&&&&input id="btnSearchAll" name="searchAll" type="button" value="全 部" /&&&&&&&&&&&&&&/p&&&&&&&&&&&&&&p&&&&&&&&&&&&&&&&&&strong&新增:&/strong&&&&&&&&&&&&&&&&&&br /&&&&&&&&&&&&&&&&&产品名称:&input id="newProductName" name="newProductName" type="text" /&&&&&&&&&&&&&&&&&产品类型:&select id="newProductType" name="newProductType" style="width: 120 height: 34"&&&&&&&&&&&&&&&&&&&&&&option value="-1"&--请选择--&/option&&&&&&&&&&&&&&&&&&&&&&option value="0"&移动电话&/option&&&&&&&&&&&&&&&&&&&&&&option value="1"&便携式计算机&/option&&&&&&&&&&&&&&&&&&&&&&option value="2"&电视游戏机&/option&&&&&&&&&&&&&&&&&&/select&&&&&&&&&&&&&&&&&&br /&&&&&&&&&&&&&&&&&产品价格:&input id="newProductPrice" name="newProductPrice" type="text" /&&&&&&&&&&&&&&&&&&input id="btnPostProduct" name="btnPostProduct" type="button" value="新 增" /&&&&&&&&&&&&&&/p&&&&&&&&&&/div&&&&&&/section&&&&&&section class="content-wrapper main-content clear-fix"&&&&&&&&&&h3&下面是从WebAPI获取的数据集:&/h3&&&&&&&&&&div id="result"&&&&&&&&&&/div&&&&&&&&&@*&ol class="round"&&&&&&&&&&&&&&li class="one"&&&&&&&&&&&&&&&&&&h5&开始使用&/h5&&&&&&&&&&&&&&&&&ASP.NET Web API&&是一个框架,您可以通过该框架轻松生成可访问&&&&&&&&&&&&&&&&多种客户端(包括浏览器和移动设备)的 HTTP 服务。ASP.NET Web API&&&&&&&&&&&&&&&&是一个用于在 .NET Framework 之上生成 REST 样式的应用程序的理想平台。&&&&&&&&&&&&&&&&&a href="/fwlink/?LinkId=245160"&了解详细信息...&/a&&&&&&&&&&&&&&/li&&&&&&&&&&/ol&*@&&&&&/section&&/div&&!-- jBox modal --&&div id="myMsgModal" class="notshow"&&/div&&!-- jBox edit modal --&&div id="myEditModal" class="notshow"&&&&&&input id="hiddProductId" type="hidden" /&&&&&&table width="100%"&&&&&&&&&&tr&&&&&&&&&&&&&&td align="right"&产品名称:&/td&&&&&&&&&&&&&&td&&&&&&&&&&&&&&&&&&input id="editProductName" name="editProductName" type="text" /&&/td&&&&&&&&&&/tr&&&&&&&&&&tr&&&&&&&&&&&&&&td align="right"&产品类型:&/td&&&&&&&&&&&&&&td&&&&&&&&&&&&&&&&&&select id="editProductType" name="editProductType" style="width: 120 height: 34"&&&&&&&&&&&&&&&&&&&&&&option value="-1"&--请选择--&/option&&&&&&&&&&&&&&&&&&&&&&option value="0"&移动电话&/option&&&&&&&&&&&&&&&&&&&&&&option value="1"&便携式计算机&/option&&&&&&&&&&&&&&&&&&&&&&option value="2"&电视游戏机&/option&&&&&&&&&&&&&&&&&&/select&&&&&&&&&&&&&&/td&&&&&&&&&&/tr&&&&&&&&&&tr&&&&&&&&&&&&&&td align="right"&产品价格:&/td&&&&&&&&&&&&&&td&&&&&&&&&&&&&&&&&&input id="editProductPrice" name="editProductPrice" type="text" /&&&&&&&&&&&&&&/td&&&&&&&&&&/tr&&&&&&&&&&tr&&&&&&&&&&&&&&td colspan="2" align="center"&&&&&&&&&&&&&&&&&&a id="btnPutProduct" href="#" class="easyui-linkbutton"&确定&/a&&&&&&&&&&&&&&&&&&a id="btnCloseModal" href="#" class="easyui-linkbutton"&关闭&/a&&&&&&&&&&&&&&/td&&&&&&&&&&/tr&&&&&&/table&&/div&@section scripts{&&&&&script src="~/Scripts/jquery-1.7.1.min.js"&&/script&&&&&&script src="~/Content/themes/easyui/jquery.easyui.min.js"&&/script&&&&&&script src="~/Content/themes/easyui/easyui-lang-zh_CN.js"&&/script&&&&&&script type="text/javascript"&&&&&&&&&$(function () {&&&&&&&&&&&&initData();&&&&&&&&&&&&bindClick();&&&&&&&&});&&&&&&&&&function initData() {&&&&&&&&&&&&$.getJSON("api/Product", function (data) {&&&&&&&&&&&&&&&&if (data != null) {&&&&&&&&&&&&&&&&&&&&if ($("#resultList").length & 0) {&&&&&&&&&&&&&&&&&&&&&&&&$("#resultList").remove();&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&var html = "&ol id='resultList' class='round'&";&&&&&&&&&&&&&&&&&&&&$.each(data, function (key, value) {&&&&&&&&&&&&&&&&&&&&&&&&html += "&li class='one'&&h5&" + value.Name + "&/h5&类型:" + value.Category&&&&&&&&&&&&&&&&&&&&&&&&&&&&+ " 价格:" + value.Price + "&&| &a href='#' onclick='editProduct(" + value.Id + ")'&编辑&/a&&a href='#' onclick='deleteProduct(" + value.Id + ")'&删除&/a&&/li&";&&&&&&&&&&&&&&&&&&&&});&&&&&&&&&&&&&&&&&&&&html += "&/ol&";&&&&&&&&&&&&&&&&&&&&$("#result").append(html);&&&&&&&&&&&&&&&&}&&&&&&&&&&&&});&&&&&&&&}&&&&&&&&&function bindClick() {&&&&&&&&&&&&// 01.按产品类型搜索产品&&&&&&&&&&&&$("#productTypes").bind("change", function () {&&&&&&&&&&&&&&&&$.getJSON("api/Product", { category: $(this).find("option:selected").text() }, function (data) {&&&&&&&&&&&&&&&&&&&&if (data != null) {&&&&&&&&&&&&&&&&&&&&&&&&$("#resultList").remove();&&&&&&&&&&&&&&&&&&&&&&&&var html = "&ol id='resultList' class='round'&";&&&&&&&&&&&&&&&&&&&&&&&&$.each(data, function (key, value) {&&&&&&&&&&&&&&&&&&&&&&&&&&&&html += "&li class='one'&&h5&" + value.Name + "&/h5&类型:" + value.Category&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&+ " 价格:" + value.Price + "&&| &a href='#' onclick='editProduct(" + value.Id + ")'&编辑&/a&&a href='#' onclick='deleteProduct(" + value.Id + ")'&删除&/a&&/li&";&&&&&&&&&&&&&&&&&&&&&&&&});&&&&&&&&&&&&&&&&&&&&&&&&html += "&/ol&";&&&&&&&&&&&&&&&&&&&&&&&&$("#result").append(html);&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&});&&&&&&&&&&&&});&&&&&&&&&&&&// 02.按产品名搜索产品&&&&&&&&&&&&$("#btnSearchByName").bind("click", function () {&&&&&&&&&&&&&&&&var searchName = $("#productName").val();&&&&&&&&&&&&&&&&if (searchName == "") {&&&&&&&&&&&&&&&&&&&&showMsg("提示", "您还没有输入要搜索的产品名称");&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&$.getJSON("api/Product", { productName: searchName }, function (data) {&&&&&&&&&&&&&&&&&&&&if (data != null) {&&&&&&&&&&&&&&&&&&&&&&&&$("#resultList").remove();&&&&&&&&&&&&&&&&&&&&&&&&var html = "&ol id='resultList' class='round'&";&&&&&&&&&&&&&&&&&&&&&&&&html += "&li class='one'&&h5&" + data.Name + "&/h5&类型:" + data.Category&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&+ " 价格:" + data.Price + "&&| &a href='#' onclick='editProduct(" + data.Id + ")'&编辑&/a&&a href='#' onclick='deleteProduct(" + data.Id + ")'&删除&/a&&/li&";&&&&&&&&&&&&&&&&&&&&&&&&html += "&/ol&";&&&&&&&&&&&&&&&&&&&&&&&&$("#result").append(html);&&&&&&&&&&&&&&&&&&&&&&&&clearText();&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&});&&&&&&&&&&&&});&&&&&&&&&&&&// 03.搜索全部产品信息&&&&&&&&&&&&$("#btnSearchAll").bind("click", initData);&&&&&&&&&&&&// 04.新增一个产品信息&&&&&&&&&&&&$("#btnPostProduct").bind("click", function () {&&&&&&&&&&&&&&&&var productName = $("#newProductName").val();&&&&&&&&&&&&&&&&var productCategory = $("#newProductType").find("option:selected").text();&&&&&&&&&&&&&&&&var productPrice = $("#newProductPrice").val();&&&&&&&&&&&&&&&&&if (productName == "") {&&&&&&&&&&&&&&&&&&&&showMsg("提示", "请输入产品名称");&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&else if (productCategory == "" || productCategory == "--请选择--") {&&&&&&&&&&&&&&&&&&&&showMsg("提示", "请选择产品类型");&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&else if (productPrice == "") {&&&&&&&&&&&&&&&&&&&&showMsg("提示", "请输入产品价格");&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&else if (isNaN(productPrice)) {&&&&&&&&&&&&&&&&&&&&showMsg("提示", "产品价格请输入数字类型");&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&else {&&&&&&&&&&&&&&&&&&&&$.post("api/Product", {&&&&&&&&&&&&&&&&&&&&&&&&Name: productName,&&&&&&&&&&&&&&&&&&&&&&&&Category: productCategory,&&&&&&&&&&&&&&&&&&&&&&&&Price: productPrice&&&&&&&&&&&&&&&&&&&&}, function (data) {&&&&&&&&&&&&&&&&&&&&&&&&if (data != null && data == true) {&&&&&&&&&&&&&&&&&&&&&&&&&&&&initData();&&&&&&&&&&&&&&&&&&&&&&&&&&&&clearText();&&&&&&&&&&&&&&&&&&&&&&&&&&&&showMsg("提示", "添加新产品操作成功");&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&else {&&&&&&&&&&&&&&&&&&&&&&&&&&&&showMsg("提示", "添加新产品操作失败");&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&});&&&&&&&&&&&&&&&&}&&&&&&&&&&&&});&&&&&&&&&&&&// 07.修改一个产品信息&&&&&&&&&&&&$("#btnPutProduct").bind("click", function () {&&&&&&&&&&&&&&&&var productId = $("#hiddProductId").val();&&&&&&&&&&&&&&&&$.ajax({&&&&&&&&&&&&&&&&&&&&type: "PUT",&&&&&&&&&&&&&&&&&&&&url: "/api/Product/" + productId,&&&&&&&&&&&&&&&&&&&&data: {&&&&&&&&&&&&&&&&&&&&&&&&Id: productId,&&&&&&&&&&&&&&&&&&&&&&&&Name: $("#editProductName").val(),&&&&&&&&&&&&&&&&&&&&&&&&Category: $("#editProductType").find("option:selected").text(),&&&&&&&&&&&&&&&&&&&&&&&&Price: $("#editProductPrice").val()&&&&&&&&&&&&&&&&&&&&},&&&&&&&&&&&&&&&&&&&&success: function (data) {&&&&&&&&&&&&&&&&&&&&&&&&if (data == true) {&&&&&&&&&&&&&&&&&&&&&&&&&&&&initData();&&&&&&&&&&&&&&&&&&&&&&&&&&&&$("#myEditModal").window("close");&&&&&&&&&&&&&&&&&&&&&&&&&&&&showMsg("提示", "您已成功修改那玩意");&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&else {&&&&&&&&&&&&&&&&&&&&&&&&&&&&showMsg("提示", "修改那玩意操作失败");&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&});&&&&&&&&&&&&});&&&&&&&&&&&&// 关闭模态对话框&&&&&&&&&&&&$("#btnCloseModal").bind("click", function () {&&&&&&&&&&&&&&&&$("#myEditModal").window("close");&&&&&&&&&&&&});&&&&&&&&}&&&&&&&&// 05.编辑一个产品信息&&&&&&&&function editProduct(productId) {&&&&&&&&&&&&$.getJSON("api/Product", { id: productId }, function (data) {&&&&&&&&&&&&&&&&if (data != null) {&&&&&&&&&&&&&&&&&&&&$("#hiddProductId").val(data.Id);&&&&&&&&&&&&&&&&&&&&$("#editProductName").val(data.Name);&&&&&&&&&&&&&&&&&&&&switch (data.Category) {&&&&&&&&&&&&&&&&&&&&&&&&case "移动电话":&&&&&&&&&&&&&&&&&&&&&&&&&&&&$("#editProductType").val("0");&&&&&&&&&&&&&&&&&&&&&&&&&&&&break;&&&&&&&&&&&&&&&&&&&&&&&&case "便携式计算机":&&&&&&&&&&&&&&&&&&&&&&&&&&&&$("#editProductType").val("1");&&&&&&&&&&&&&&&&&&&&&&&&&&&&break;&&&&&&&&&&&&&&&&&&&&&&&&case "电视游戏机":&&&&&&&&&&&&&&&&&&&&&&&&&&&&$("#editProductType").val("2");&&&&&&&&&&&&&&&&&&&&&&&&&&&&break;&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&$("#editProductPrice").val(data.Price);&&&&&&&&&&&&&&&&}&&&&&&&&&&&&});&&&&&&&&&&&&$("#myEditModal").show();&&&&&&&&&&&&$("#myEditModal").window({&&&&&&&&&&&&&&&&title: "编辑产品信息",&&&&&&&&&&&&&&&&modal: true,&&&&&&&&&&&&&&&&collapsible: true,&&&&&&&&&&&&&&&&minimizable: false,&&&&&&&&&&&&&&&&maximizable: false,&&&&&&&&&&&&&&&&resizable: false,&&&&&&&&&&&&&&&&width: 500,&&&&&&&&&&&&&&&&height: 220&&&&&&&&&&&&});&&&&&&&&}&&&&&&&&// 06.删除一个产品信息&&&&&&&&function deleteProduct(productId) {&&&&&&&&&&&&$.messager.confirm("提示", "您确定要删除这玩意?", function (r) {&&&&&&&&&&&&&&&&if (r) {&&&&&&&&&&&&&&&&&&&&$.ajax({&&&&&&&&&&&&&&&&&&&&&&&&type: "DELETE",&&&&&&&&&&&&&&&&&&&&&&&&url: "/api/Product/" + productId,&&&&&&&&&&&&&&&&&&&&&&&&data: {},&&&&&&&&&&&&&&&&&&&&&&&&success: function (data) {&&&&&&&&&&&&&&&&&&&&&&&&&&&&if (data == true) {&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&initData();&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&showMsg("提示", "您已成功删除那玩意");&&&&&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&&&&&else {&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&showMsg("提示", "删除那玩意操作失败");&&&&&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&});&&&&&&&&&&&&&&&&}&&&&&&&&&&&&});&&&&&&&&}&&&&&&&&&function showMsg(title, msg) {&&&&&&&&&&&&$.messager.alert(title, msg, "info");&&&&&&&&}&&&&&&&&&function clearText() {&&&&&&&&&&&&$("input[type=text]").val("");&&&&&&&&}&&&&&/script&}
通过调试运行,可以看到以下页面效果,并可以看到,由于我们在页面中加入了获取产品列表的GET请求,于是产品信息被加载到了页面中:
其对应的JS语句为:可以看到,我们通过api/Product调用了API控制器中的GetAllProducts方法,获取了所有产品信息。
$.getJSON("api/Product", function (data) {
if (data != null) {
if ($("#resultList").length & 0) {
$("#resultList").remove();
var html = "&ol id='resultList' class='round'&";
$.each(data, function (key, value) {
html += "&li class='one'&&h5&" + value.Name + "&/h5&类型:" + value.Category
+ " 价格:" + value.Price + "
| &a href='#' onclick='editProduct(" + value.Id + ")'&编辑&/a&&a href='#' onclick='deleteProduct(" + value.Id + ")'&删除&/a&&/li&";
html += "&/ol&";
$("#result").append(html);
123456789101112131415
$.getJSON("api/Product", function (data) {&&&&&&&&&&&&&&&&if (data != null) {&&&&&&&&&&&&&&&&&&&&if ($("#resultList").length & 0) {&&&&&&&&&&&&&&&&&&&&&&&&$("#resultList").remove();&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&var html = "&ol id='resultList' class='round'&";&&&&&&&&&&&&&&&&&&&&$.each(data, function (key, value) {&&&&&&&&&&&&&&&&&&&&&&&&html += "&li class='one'&&h5&" + value.Name + "&/h5&类型:" + value.Category&&&&&&&&&&&&&&&&&&&&&&&&&&&&+ " 价格:" + value.Price + "&&| &a href='#' onclick='editProduct(" + value.Id + ")'&编辑&/a&&a href='#' onclick='deleteProduct(" + value.Id + ")'&删除&/a&&/li&";&&&&&&&&&&&&&&&&&&&&});&&&&&&&&&&&&&&&&&&&&html += "&/ol&";&&&&&&&&&&&&&&&&&&&&$("#result").append(html);&&&&&&&&&&&&&&&&}});
(8)下面我们可以来试试其他的API方法:
3.4 第一个RestClient客户端项目
有了我们上面的WebAPI项目的支持,我们可以在客户端(如:WindowsForm项目、Windows Phone项目等等)对WebAPI项目中的资源进行访问和操作,现在我们就来实现一个RestClient控制台项目模拟一个客户端对WebAPI发起HTTP访问请求。
(1)新建一个控制台项目,取名为:MyConsoleRestClientDemo。
(2)新建一个类,取名为:RestClient.cs。它封装了我们常用的HTTP操作,如GET、POST、PUT、DELETE方式。
public class RestClient
private string BaseU
public RestClient(string baseUri)
this.BaseUri = baseU
#region Delete方式
public string Delete(string data, string uri)
return CommonHttpRequest(data, uri, "DELETE");
public string Delete(string uri)
//Web访问对象64
string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
myRequest.Method = "DELETE";
// 获得接口返回值68
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
//string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
string ReturnXml = reader.ReadToEnd();
reader.Close();
myResponse.Close();
return ReturnX
#endregion
#region Put方式
public string Put(string data, string uri)
return CommonHttpRequest(data, uri, "PUT");
#endregion
#region POST方式实现
public string Post(string data, string uri)
return CommonHttpRequest(data, uri, "POST");
public string CommonHttpRequest(string data, string uri, string type)
//Web访问对象,构造请求的url地址
string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
//构造http请求的对象
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
//转成网络流
byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);
myRequest.Method =
myRequest.ContentLength = buf.L
myRequest.ContentType = "application/json";
myRequest.MaximumAutomaticRedirections = 1;
myRequest.AllowAutoRedirect =
// 发送请求
Stream newStream = myRequest.GetRequestStream();
newStream.Write(buf, 0, buf.Length);
newStream.Close();
// 获得接口返回值
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
string ReturnXml = reader.ReadToEnd();
reader.Close();
myResponse.Close();
return ReturnX
#endregion
#region GET方式实现
public string Get(string uri)
//Web访问对象64
string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);
//构造一个Web请求的对象
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);
// 获得接口返回值68
//获取web请求的响应的内容
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
//通过响应流构造一个StreamReader
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
//string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());
string ReturnXml = reader.ReadToEnd();
reader.Close();
myResponse.Close();
return ReturnX
#endregion
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
public class RestClient&&&&{&&&&&&&&private string BaseUri;&&&&&&&&public RestClient(string baseUri)&&&&&&&&{&&&&&&&&&&&&this.BaseUri = baseUri;&&&&&&&&}&&&&&&&&&#region Delete方式&&&&&&&&public string Delete(string data, string uri)&&&&&&&&{&&&&&&&&&&&&return CommonHttpRequest(data, uri, "DELETE");&&&&&&&&}&&&&&&&&&public string Delete(string uri)&&&&&&&&{&&&&&&&&&&&&//Web访问对象64&&&&&&&&&&&&string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);&&&&&&&&&&&&HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);&&&&&&&&&&&&myRequest.Method = "DELETE";&&&&&&&&&&&&// 获得接口返回值68&&&&&&&&&&&&HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();&&&&&&&&&&&&StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);&&&&&&&&&&&&//string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());&&&&&&&&&&&&string ReturnXml = reader.ReadToEnd();&&&&&&&&&&&&reader.Close();&&&&&&&&&&&&myResponse.Close();&&&&&&&&&&&&return ReturnXml;&&&&&&&&}&&&&&&&&#endregion&&&&&&&&&#region Put方式&&&&&&&&public string Put(string data, string uri)&&&&&&&&{&&&&&&&&&&&&return CommonHttpRequest(data, uri, "PUT");&&&&&&&&}&&&&&&&&#endregion&&&&&&&&&#region POST方式实现&&&&&&&&&public string Post(string data, string uri)&&&&&&&&{&&&&&&&&&&&&return CommonHttpRequest(data, uri, "POST");&&&&&&&&}&&&&&&&&&public string CommonHttpRequest(string data, string uri, string type)&&&&&&&&{&&&&&&&&&&&&//Web访问对象,构造请求的url地址&&&&&&&&&&&&string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);&&&&&&&&&&&&&//构造http请求的对象&&&&&&&&&&&&HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);&&&&&&&&&&&&//转成网络流&&&&&&&&&&&&byte[] buf = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(data);&&&&&&&&&&&&//设置&&&&&&&&&&&&myRequest.Method = type;&&&&&&&&&&&&myRequest.ContentLength = buf.Length;&&&&&&&&&&&&myRequest.ContentType = "application/json";&&&&&&&&&&&&myRequest.MaximumAutomaticRedirections = 1;&&&&&&&&&&&&myRequest.AllowAutoRedirect = true;&&&&&&&&&&&&// 发送请求&&&&&&&&&&&&Stream newStream = myRequest.GetRequestStream();&&&&&&&&&&&&newStream.Write(buf, 0, buf.Length);&&&&&&&&&&&&newStream.Close();&&&&&&&&&&&&// 获得接口返回值&&&&&&&&&&&&HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();&&&&&&&&&&&&StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);&&&&&&&&&&&&string ReturnXml = reader.ReadToEnd();&&&&&&&&&&&&reader.Close();&&&&&&&&&&&&myResponse.Close();&&&&&&&&&&&&return ReturnXml;&&&&&&&&}&&&&&&&&#endregion&&&&&&&&&#region GET方式实现&&&&&&&&public string Get(string uri)&&&&&&&&{&&&&&&&&&&&&//Web访问对象64&&&&&&&&&&&&string serviceUrl = string.Format("{0}/{1}", this.BaseUri, uri);&&&&&&&&&&&&&//构造一个Web请求的对象&&&&&&&&&&&&HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl);&&&&&&&&&&&&// 获得接口返回值68&&&&&&&&&&&&//获取web请求的响应的内容&&&&&&&&&&&&HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();&&&&&&&&&&&&&//通过响应流构造一个StreamReader&&&&&&&&&&&&StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);&&&&&&&&&&&&//string ReturnXml = HttpUtility.UrlDecode(reader.ReadToEnd());&&&&&&&&&&&&string ReturnXml = reader.ReadToEnd();&&&&&&&&&&&&reader.Close();&&&&&&&&&&&&myResponse.Close();&&&&&&&&&&&&return ReturnXml;&&&&&&&&}&&&&&&&&#endregion&&&&}
(3)在Program.cs中的Main方法中,调用RestClient类为我们提供的方法对WebAPI服务器(这里是本机:http://localhost:8080/)发起访问:
class Program
static string restfulServiceUri = "http://localhost:8080/";
static void Main(string[] args)
RestClient restClient = new RestClient(restfulServiceUri);
#region 01.Get方式无参数请求
Console.WriteLine("----------------------获取所有产品列表-----------------------");
string getResult = restClient.Get("api/Product");
Console.WriteLine(getResult);
Console.WriteLine();
#endregion
#region 02.Get方式带参数请求
Console.WriteLine("----------------------获取Id=1的产品信息-----------------------");
string getByIdResult = restClient.Get("api/Product/1");
Console.WriteLine(getByIdResult);
Console.WriteLine();
Console.WriteLine("----------------------获取Name=锤子手机的产品信息-----------------------");
string getByNameResult = restClient.Get("api/Product/?productName=锤子手机");
Console.WriteLine(getByNameResult);
Console.WriteLine();
Console.WriteLine("----------------------获取Category=移动电话的产品信息-----------------------");
string getByTypeResult = restClient.Get("api/Product/?category=移动电话");
Console.WriteLine(getByTypeResult);
Console.WriteLine();
#endregion
#region 03.Post方式请求结果
//Console.WriteLine("----------------------新增一个产品信息-----------------------");
//string jsonParam = @"{Id:""250"",Name:""小米2S"",Category:""移动电话"",Price:""1800""}";
//string postResult = restClient.Post(jsonParam, "api/Product");
//Console.WriteLine(postResult);
//getResult = restClient.Get("api/Product");
//Console.WriteLine(getResult);
//Console.WriteLine();
#endregion
#region 04.Delete方式请求结果
//Console.WriteLine("----------------------删除一个产品信息-----------------------");
//string deleteId = "6";
//string deleteResult = restClient.Delete("api/Product/" + deleteId);
//Console.WriteLine(deleteResult);
//getResult = restClient.Get("api/Product");
//Console.WriteLine(getResult);
//Console.WriteLine();
#endregion
#region 05.Put方式请求结果
Console.WriteLine("----------------------修改一个产品信息-----------------------");
string jsonParam = @"{Id:""5"",Name:""PlayStation 3"",Category:""电视游戏机"",Price:""3200""}";
string putResult = restClient.Put(jsonParam, "api/Product/5");
Console.WriteLine(putResult);
getResult = restClient.Get("api/Product");
Console.WriteLine(getResult);
Console.WriteLine();
#endregion
Console.ReadKey();
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
class Program&&&&{&&&&&&&&static string restfulServiceUri = "http://localhost:8080/";&&&&&&&&&static void Main(string[] args)&&&&&&&&{&&&&&&&&&&&&RestClient restClient = new RestClient(restfulServiceUri);&&&&&&&&&&&&&#region 01.Get方式无参数请求&&&&&&&&&&&&Console.WriteLine("----------------------获取所有产品列表-----------------------");&&&&&&&&&&&&string getResult = restClient.Get("api/Product");&&&&&&&&&&&&Console.WriteLine(getResult);&&&&&&&&&&&&Console.WriteLine();&&&&&&&&&&&&#endregion&&&&&&&&&&&&&#region 02.Get方式带参数请求&&&&&&&&&&&&Console.WriteLine("----------------------获取Id=1的产品信息-----------------------");&&&&&&&&&&&&string getByIdResult = restClient.Get("api/Product/1");&&&&&&&&&&&&Console.WriteLine(getByIdResult);&&&&&&&&&&&&Console.WriteLine();&&&&&&&&&&&&Console.WriteLine("----------------------获取Name=锤子手机的产品信息-----------------------");&&&&&&&&&&&&string getByNameResult = restClient.Get("api/Product/?productName=锤子手机");&&&&&&&&&&&&Console.WriteLine(getByNameResult);&&&&&&&&&&&&Console.WriteLine();&&&&&&&&&&&&Console.WriteLine("----------------------获取Category=移动电话的产品信息-----------------------");&&&&&&&&&&&&string getByTypeResult = restClient.Get("api/Product/?category=移动电话");&&&&&&&&&&&&Console.WriteLine(getByTypeResult);&&&&&&&&&&&&Console.WriteLine();&&&&&&&&&&&&#endregion&&&&&&&&&&&&&#region 03.Post方式请求结果&&&&&&&&&&&&//Console.WriteLine("----------------------新增一个产品信息-----------------------");&&&&&&&&&&&&//string jsonParam = @"{Id:""250"",Name:""小米2S"",Category:""移动电话"",Price:""1800""}";&&&&&&&&&&&&//string postResult = restClient.Post(jsonParam, "api/Product");&&&&&&&&&&&&//Console.WriteLine(postResult);&&&&&&&&&&&&//getResult = restClient.Get("api/Product");&&&&&&&&&&&&//Console.WriteLine(getResult);&&&&&&&&&&&&//Console.WriteLine();&&&&&&&&&&&&#endregion&&&&&&&&&&&&&#region 04.Delete方式请求结果&&&&&&&&&&&&//Console.WriteLine("----------------------删除一个产品信息-----------------------");&&&&&&&&&&&&//string deleteId = "6";&&&&&&&&&&&&//string deleteResult = restClient.Delete("api/Product/" + deleteId);&&&&&&&&&&&&//Console.WriteLine(deleteResult);&&&&&&&&&&&&//getResult = restClient.Get("api/Product");&&&&&&&&&&&&//Console.WriteLine(getResult);&&&&&&&&&&&&//Console.WriteLine();&&&&&&&&&&&&#endregion&&&&&&&&&&&&&#region 05.Put方式请求结果&&&&&&&&&&&&Console.WriteLine("----------------------修改一个产品信息-----------------------");&&&&&&&&&&&&string jsonParam = @"{Id:""5"",Name:""PlayStation 3"",Category:""电视游戏机"",Price:""3200""}";&&&&&&&&&&&&string putResult = restClient.Put(jsonParam, "api/Product/5");&&&&&&&&&&&&Console.WriteLine(putResult);&&&&&&&&&&&&getResult = restClient.Get("api/Product");&&&&&&&&&&&&Console.WriteLine(getResult);&&&&&&&&&&&&Console.WriteLine();&&&&&&&&&&&&#endregion&&&&&&&&&&&&&Console.ReadKey();&&&&&&&&}&&&&}
(4)调试运行,查看访问结果如下:可以看出,返回的均为JSON格式的数据,和我们在浏览器中访问指定URI的结果一致。
3.5 初探小结
ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务。 ASP.NET Web API 是一种用于在 .NET Framework 上构建 RESTful 应用程序的理想平台。
(1)搏击的小船,《ASP.NET MVC2 Areas区域新概念》,/guanjie20/archive//1822175.html
(2)游响云停,《ASP.NET MVC3细嚼慢咽-(2)模板页 》,http://blog.csdn.net/zx/article/details/8301943
(3)李林峰,《无废话MVC入门教程四[视图中的Layout使用]》,/iamlilinfeng/archive//2934397.html
(4)阮一峰,《理解Restful架构》,/blog/2011/09/restful.html
(5)便当之神,《ASP.Net WebAPI》,/bnbqian/archive//2565417.html
(6)dudu,《HttpClient + ASP.NET Web API, WCF之外的另一个选择》,/dudu/archive//asp_net_webapi_httpclient.html
(1)MyWebAPIDemo:
可能感兴趣的话题
关于伯乐在线博客
在这个信息爆炸的时代,人们已然被大量、快速并且简短的信息所包围。然而,我们相信:过多“快餐”式的阅读只会令人“虚胖”,缺乏实质的内涵。伯乐在线内容团队正试图以我们微薄的力量,把优秀的原创文章和译文分享给读者,为“快餐”添加一些“营养”元素。
新浪微博:
推荐微信号
(加好友请注明来意)
– 好的话题、有启发的回复、值得信赖的圈子
– 分享和发现有价值的内容与观点
– 为IT单身男女服务的征婚传播平台
– 优秀的工具资源导航
– 翻译传播优秀的外文文章
– 国内外的精选文章
– UI,网页,交互和用户体验
– 专注iOS技术分享
– 专注Android技术分享
– JavaScript, HTML5, CSS
– 专注Java技术分享
– 专注Python技术分享
& 2016 伯乐在线}

我要回帖

更多关于 web api 身份验证 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信