博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
MVC4 WEBAPI(一)使用概述
阅读量:4625 次
发布时间:2019-06-09

本文共 7771 字,大约阅读时间需要 25 分钟。

所谓概述,也就是总结一些WEB API常用的使用用法。MVC APIWEB是一个轻量级的服务接口,完全符合RestFul框架设计,每个URL代表一种资源,使用方便,没有WCF那么庞大,但是麻雀虽小五脏俱全,WEBAPI提供的内容很值得研究;API请求方式有GET、POST、PUT、DELETE。所以WEBAPI对应的APIControl提供的接口也分为以上4个类型。

1、WEBAPI创建:

    使用的时候也很简单,利用VS2013新建项目,选择MVC4,让后选择WEBAPI,创建完成,这就是默认的MVC WEBAPI项目;

2、WEBAPI分析:

  WEB API默认的路由是:

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

这个是默认提供的路由,通过路由,我们不难发现通过Control下的id进行匹配查找,所以接下的代码也是根据ID进行处理;由于服务请求的方式GET、POST、DELETE、PUT,所以每个APIControl也就提供这4中类型,针对这个轻量级框架,这4中方式处理好,一个APIControl应对自己的逻辑也就足够了。

代码展示:

public class ProductController : ApiController    {        static List
products =new List
() { 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} }; ///
/// Get /// ///
public IEnumerable
GetAllProducts() { return products.OrderBy(p => p.Id); } ///
/// Get /// ///
///
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; } ///
/// Get /// ///
///
public Product GetProductByName(string productName,string category) { Product product = products.FirstOrDefault(p => p.Name.Contains(productName) && p.Category == category); if (product == null) { var resp = new HttpResponseMessage(HttpStatusCode.NotFound); throw new HttpResponseException(resp); } return product; } public IEnumerable
GetAllProductsByCategory(string category) { if (category.Equals("--请选择--")) { return products; } IEnumerable
productList = products.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)); return productList.OrderBy(p => p.Id); } 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; } //public IEnumerable
PostProductByCategory(string Category) //{ // //if (currpate.Category.Equals("--请选择--")) // //{ // // return products; // //} // //IEnumerable
productList = products.Where(p => string.Equals(p.Category, currpate.Category, StringComparison.OrdinalIgnoreCase)); // return products;// productList.OrderBy(p => p.Id); //} //public IEnumerable
PostProductByCategory22([FromBody] JObject currpate) //{ // dynamic json = currpate; // JObject curtxt = json.prodcut; // //if (currpate.Category.Equals("--请选择--")) // //{ // // return products; // //} // //IEnumerable
productList = products.Where(p => string.Equals(p.Category, currpate.Category, StringComparison.OrdinalIgnoreCase)); // return products;// productList.OrderBy(p => p.Id); //} 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; } ///
/// DELETE /// ///
///
public bool DeleteProduct(int id) { Product product = products.FirstOrDefault(p => p.Id == id); if (product == null) { return false; } else { products.Remove(product); return true; } } }}

代码分析:

以上就是一个简单的ControlAPI,通过代码分析,一个APIControl也就包含4中请求方式,准对GET方式请求,我们就要仔细区分ID参数进行逻辑判断。

看看客户端JS请求的方式:

JS也就是采用数据请求的方式,Ajax请求完成数据操作。

3、WEB API路由扩展:

在MVC中,大家看到的更多的路由模式是含有Action,可是WEBAPI就没有了,当然如果想使用自定义路由模式展现Action也是可行的,注册自定义路由

public static void Register(HttpConfiguration config)        {            //自定义路由            config.Routes.MapHttpRoute(                name: "DefaultSprtApi",                routeTemplate: "api/{controller}/{action}/{id}",                defaults: new { id = RouteParameter.Optional }            );            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );            // 取消注释下面的代码行可对具有 IQueryable 或 IQueryable
返回类型的操作启用查询支持。 // 若要避免处理意外查询或恶意查询,请使用 QueryableAttribute 上的验证设置来验证传入查询。 // 有关详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=279712。 //config.EnableQuerySupport(); // 若要在应用程序中禁用跟踪,请注释掉或删除以下代码行 // 有关详细信息,请参阅: http://www.asp.net/web-api config.EnableSystemDiagnosticsTracing(); }

  这这个里面,我们就把Action 加载里面了,有了这个Action,那么我们的APIControl又该怎么操作,才能获取我们想要的数据。不着急,这就展示APIControl代码

public IEnumerable
PostProductByCategory22([FromBody] JObject currpate) { dynamic json = currpate; JObject curtxt = json.prodcut; //if (currpate.Category.Equals("--请选择--")) //{ // return products; //} //IEnumerable
productList = products.Where(p => string.Equals(p.Category, currpate.Category, StringComparison.OrdinalIgnoreCase)); return products;// productList.OrderBy(p => p.Id); }

代码参数中多了一个FromBody,FromBody有什么功能那?查询CSDN发现,FromBody能够强制APIControl通过客户端或者Body读取参数,所以看看JS代码:

var prodcut = {                    Category: "移动电话",                    Price:253,                        Id:5                };                var prodcut2 = {                    Category: "移动电话2",                    Price: 253,                    Id: 5                };                $.ajax({                    type: "POST",                    url: "../api/Product/PostProductByCategory",                    data: JSON.stringify({ prot: prodcut }),                    contentType: "application/json",                    dataType:"xml",                    success: function (data) {                        console.log(data);                            if (data != null) {                                $("#resultList").remove();                                var html = "
    "; $.each(data, function (key, value) { html += "
  1. " + value.Name + "
    类型:" + value.Category + " 价格:" + value.Price + " | 编辑删除
  2. "; }); html += "
"; $("#result").append(html); } } });

使用这个地方这种方式,客户端需要注意事项:

1、需要设置请求content-Type。这里设置为contentType: "application/json";

2、发送的数据格式JSon.

服务端ControlAPI也需要注意,这个只能设置一个类型为FromBody参数,所以逻辑一定要封装好。

 参考文章:

MVC:

 

转载于:https://www.cnblogs.com/xibei666/p/5140407.html

你可能感兴趣的文章
互评Alpha版本——Thunder团队
查看>>
點擊按鈕后彈出新頁面導致原頁面CSS失效
查看>>
python--匿名函数、文件操作
查看>>
css第一课
查看>>
KindEditor的简单使用,以及上传图片预览图片,用户删除图片后的数据处理(重点),以及 BeautifulSoup,shutil两模块了解...
查看>>
Oracle数据库之PL/SQL程序设计简介
查看>>
《DSP using MATLAB》Problem 5.32
查看>>
[LeetCode] 96. Unique Binary Search Trees 唯一二叉搜索树
查看>>
[LeetCode] 685. Redundant Connection II 冗余的连接之 II
查看>>
[LeetCode] 843. Guess the Word 猜单词
查看>>
c# 技巧
查看>>
foreach 和 for 循环的区别
查看>>
说话人识别/声纹识别的研究综述(转)
查看>>
如何烧写BIOS到SD卡里面
查看>>
3-C++程序的结构1.1
查看>>
第十八课 Gazebo仿真器
查看>>
g2o:一种图优化的C++框架
查看>>
微信自定义菜单errcode(40016)
查看>>
十天冲刺-09
查看>>
python格式化输出的方式汇总
查看>>