·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设开发 >> ASP.NET网站开发 >> ASP.NET Web API 开篇示例介绍

ASP.NET Web API 开篇示例介绍

作者:佚名      ASP.NET网站开发编辑:admin      更新时间:2022-07-23

asp.net Web API 开篇示例介绍

ASP.NET Web API 开篇示例介绍

ASP.NET Web API

对于我这个初学者来说ASP.NET Web API这个框架很陌生又熟悉着。

陌生的是ASP.NET Web API是一个全新的框架,对于这个框架在一个项目中起到的作用我暂且还不是很清楚这里也就不妄下结论了,说实话不是我不想而是我无能为力,只能自己去摸索试着去了解它。

熟悉的是ASP.NET Web API跟ASP.NET MVC的框架结构一开始看起来有一些相似的地方。

话就不多说了,大家就和我一起来学习ASP.NET Web API这个全新的框架吧。

ASP.NET Web API演示示例

环境基础配置

首先我们新建一个类库项目命名为Common,并且定义个货品信息类型,示例代码如下:

代码1-1

namespace Common{    public class PRoduct    {        public string ProductID { get; set; }        public string ProductName { get; set; }        public string ProductCategory { get; set; }    }}

建立WebHost宿主环境

然后我们接着创建一个空的ASP.NET WEB应用程序命名为WebHost,这里说明一下ASP.NET Web API框架只是个独立框架,它并不能独立运行,所以它需要宿主环境,刚刚我们新建的WEB应用程序则会在下面的示例中暂时的承载着ASP.NET Web API框架来运行。

引用程序集

Newtonsoft.Json.dll 路径: C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Newtonsoft.Json.4.5.6\lib\net40Newtonsoft.Json.dll

System.Net.Http.dll 路径:C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\ System.Net.Http.dll

System.Net.Http.Formatting.dll路径:C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\ System.Net.Http.Formatting.dll

System.Web.Http.dll 路径:C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\ System.Web.Http.dll

System.Web.Http.WebHost.dll路径:C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\System.Web.Http.WebHost.dll

Common.dll (项目引用)

或者采用这种引用方式:

(如果上文中所述的目录位置没有Newtonsoft.Json.dll的话可以文件搜索一下,然后手动引用。)

随之我们再建立一个Web应用程序处理类Globl.asax ,并在其application_Start()方法中注册路由,示例代码如下:

代码1-2

using System.Web.Http;namespace WebHost{    public class Global : System.Web.HttpApplication    {        protected void Application_Start(object sender, EventArgs e)        {            GlobalConfiguration.Configuration.Routes.MapHttpRoute(              "DefaultAPI", "api/{controller}/{id}", new { controller="product",id = RouteParameter.Optional });        }    }}

路由注册好了之后,我们还得新建个Web API控制器,命名为ProductController,示例代码如下:

代码1-3

using System.Web.Http;using Common;namespace WebHost.Controllers{    public class ProductController:ApiController    {        private static List<Product> products;        static ProductController()        {            products = new List<Product>();            products.AddRange(                new Product[]                 {                    new Product(){ ProductID="001", ProductName="牙刷",ProductCategory="洗漱用品"},                    new Product(){ ProductID="002", ProductName="《.NET框架设计—大型企业级应用框架设计艺术》", ProductCategory="书籍"}                });        }        public IEnumerable<Product> Get(string id = null)        {            return from product in products where product.ProductID == id || string.IsNullOrEmpty(id) select product;        }    }}

在代码1-3中我们看到ProductController控制器继承自ApiController,这里的方式我的猜想应该是跟ASP.NET MVC框架对控制器的处理一样,在请求到来之后并且经过路由处理之后,Web API框架会把当前项目中所有引用的程序集全部查找一下并且搜出继承自ApiController的类型,并且缓存在一个xml文件,不知道猜想的对不对在后面的篇幅我们再来验证,这里提一下。

细心的朋友的可能发现在路由注册的时候并没有对应的Action的路由参数,其实这里就是Web API框架的一个不同之处,它是根据Http请求方法来确定Action的方法的,然而浏览器默认的请求方法就是Http-get,所以我们这个时候可以直接运行项目。

图2

建立SelfHost

下面我们来看一下在SelfHost宿主环境中ASP.NET Web API框架的使用示例。

首先我们新建一个控制台应用程序命名为SelfHost,SelfHost环境项目的程序集引用和上面所说的WebHost项目引用唯一不同的就是把System.Web.Http.WebHost.dll程序集换成System.Web.Http.SelfHost.dll程序集,引用路径不变,也可以利用引用里的扩展栏来添加。

下面就让我们看一下在SelfHost中我们需要做哪些事,首先我们需要注册路由这是每次最先做的事情,示例代码如下:

代码1-4

using System.Web.Http;using System.Web.Http.SelfHost;namespace SelfHost{    class Program    {        static void Main(string[] args)        {            HttpSelfHostConfiguration selfHostConfiguration =                new HttpSelfHostConfiguration("http://localhost/selfhost");            using (HttpSelfHostServer selfHostServer = new HttpSelfHostServer(selfHostConfiguration))            {                selfHostServer.Configuration.Routes.MapHttpRoute(                    "DefaultApi", "api/{controller}/{id}", new { id=RouteParameter.Optional});                selfHostServer.OpenAsync();                Console.WriteLine("服务器端服务监听已开启");                Console.Read();            }        }    }}

这里就简要的说明一下,在1-4代码中HttpSelfHostConfiguration对象示例中设置了基地址,对于HttpSelfHostConfiguration类型它是继承自HttpConfiguration类型,HttpConfiguration类型是比较重要的一个类型,WebAPI框架中大多数的配置信息都在此类型实例中进行设置。在后续的篇幅中会有说到。

HttpSelfHostServer对象就是在SelfHost宿主环境中担当着很重要的角色,它负责处理请求等一系列操作(因为它是WebAPI框架在SelfHost环境中的管道模型的“龙头”),在这里只要稍作了解就行了,会在后面的管道篇幅揭开它的神秘面纱。

继续向下看我们会看到HttpSelfHostServer对象实例中的Configuration属性里的Routes属性提供了对路由的注册,这部分内容会在后面的路由篇幅讲解。

再之后就是我们看到的,打开服务监听,等待处理请求。(这里的监听/处理请求,并不是对真正的请求进行处理,而是对已经请求被封装好了的对象进行处理,管道篇幅中讲解)

在路由注册之后我们要新建个Web API控制器,就如同上面WebHost部分内容一样,拷贝一份过来,不过我们这里要对控制器的代码稍作修改,示例代码如下:

代码1-5

using System.Web.Http;using Common;namespace SelfHost.Controllers{    public class ProductController:ApiController    {        private static List<Product> products;        static ProductController()        {            products = new List<Product>();            products.AddRange(                new Product[]                 {                    new Product(){ ProductID="001", ProductName="牙刷",ProductCategory="洗漱用品"},                    new Product(){ ProductID="002", ProductName="《.NET框架设计—大型企业级应用框架设计艺术》", ProductCategory="书籍"}                });        }        public IEnumerable<Product> Get(string id = null)        {            return from product in products where product.ProductID == id || string.IsNullOrEmpty(id) select product;        }        public void Delete(string id)        {            products.Remove(products.First(product => product.ProductID == id));        }        public void Post(Product product)        {            products.Add(product);        }        public void Put(Product product)        {            Delete(product.ProductID);            Post(product);        }    }}

对于在代码1-5中控制器新增的几个Action方法,也是分别对应着Http请求方法。这样也就是能实现增删改查的基础功能了。那我们还需要一个对它进行访问的客户端。

建立Clinet

我们再建一个控制台应用程序命名为Clinet,并且添加如下程序集引用:

Newtonsoft.Json.dll 路径: C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Newtonsoft.Json.4.5.6\lib\net40Newtonsoft.Json.dll

System.Net.Http.dll 路径:C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\ System.Net.Http.dll

System.Net.Http.Formatting.dll路径:C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies\ System.Net.Http.Formatting.dll

Common.dll (项目引用)

下面我们看一下在Client项目中对SelfHost环境中的资源进行访问的示例,示例代码如下:

代码1-6

using Common;using System.Net.Http;namespace Client{    class Program    {        static void Main(string[] args)        {            AsyncProcess();            Console.Read();        }        private async static void AsyncProcess()        {            HttpClient httpClient = new HttpClient();            //获取货品信息列表            HttpResponseMessage responseMessage =                await httpClient.GetAsync("http://localhost/selfhost/api/product");            IEnumerable<Product> products = await responseMessage.Content.ReadAsAsync<IEnumerable<Product>>();            OutputProductInfo(products);            //添加货品            Product product = new Product()            {                ProductID = "003",                ProductName = "《ASP.NET Web API 2 框架揭秘》",                ProductCategory = "食品类"            };            await httpClient.PostAsJsonAsync<Product>("http://localhost/selfhost/api/product", product);            responseMessage = await httpClient.GetAsync("http://localhost/selfho