温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

ASP.NET Web API示例分析

发布时间:2021-12-06 15:19:01 来源:亿速云 阅读:100 作者:iii 栏目:编程语言

这篇文章主要介绍“ASP.NET Web API示例分析”,在日常操作中,相信很多人在ASP.NET Web API示例分析问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”ASP.NET Web API示例分析”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

ASP.NET Web API演示示例

环境基础配置

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

代码1-1

namespaceCommon
{
   publicclassProduct
   {
        publicstringProductID { get; set; }
        publicstringProductName { get; set; }
        publicstringProductCategory { 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 (项目引用)

或者采用这种引用方式:

ASP.NET Web API示例分析

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

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

代码1-2

usingSystem.Web.Http;
 
namespaceWebHost
{
   publicclassGlobal : System.Web.HttpApplication
   {
        protectedvoidApplication_Start(objectsender, EventArgse)
        {
            GlobalConfiguration.Configuration.Routes.MapHttpRoute(
              "DefaultAPI", "api/{controller}/{id}", new { controller="product",id=RouteParameter.Optional });
        }
   }
}

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

代码1-3

usingSystem.Web.Http;
usingCommon;
 
namespaceWebHost.Controllers
{
   publicclassProductController:ApiController
   {
        privatestaticList<Product>products;
 
        staticProductController()
        {
            products=newList<Product>();
            products.AddRange(
                newProduct[] 
                {
                    newProduct(){ ProductID="001", ProductName="牙刷",ProductCategory="洗漱用品"},
                    newProduct(){ ProductID="002", ProductName="《.NET框架设计—大型企业级应用框架设计艺术》", ProductCategory="书籍"}
                });
        }
 
        publicIEnumerable<Product>Get(stringid=null)
        {
            returnfromproductinproductswhereproduct.ProductID==id||string.IsNullOrEmpty(id) selectproduct;
        }
   }
}

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

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

图2

ASP.NET Web API示例分析

建立SelfHost

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

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

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

代码1-4

usingSystem.Web.Http;
usingSystem.Web.Http.SelfHost;
 
namespaceSelfHost
{
   classProgram
   {
        staticvoidMain(string[] args)
        {
            HttpSelfHostConfigurationselfHostConfiguration=
                newHttpSelfHostConfiguration("http://localhost/selfhost");
            using (HttpSelfHostServerselfHostServer=newHttpSelfHostServer(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环境中的管道模型的&ldquo;龙头&rdquo;),在这里只要稍作了解就行了,会在后面的管道篇幅揭开它的神秘面纱。

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

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

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

代码1-5

usingSystem.Web.Http;
usingCommon;
 
namespaceSelfHost.Controllers
{
   publicclassProductController:ApiController
   {
        privatestaticList<Product>products;
 
        staticProductController()
        {
            products=newList<Product>();
            products.AddRange(
                newProduct[] 
                {
                    newProduct(){ ProductID="001", ProductName="牙刷",ProductCategory="洗漱用品"},
                    newProduct(){ ProductID="002", ProductName="《.NET框架设计—大型企业级应用框架设计艺术》", ProductCategory="书籍"}
                });
        }
 
 
        publicIEnumerable<Product>Get(stringid=null)
        {
            returnfromproductinproductswhereproduct.ProductID==id||string.IsNullOrEmpty(id) selectproduct;
        }
 
 
        publicvoidDelete(stringid)
        {
            products.Remove(products.First(product=>product.ProductID==id));
        }
 
        publicvoidPost(Productproduct)
        {
            products.Add(product);
        }
 
        publicvoidPut(Productproduct)
        {
            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

usingCommon;
usingSystem.Net.Http;
 
namespaceClient
{
   classProgram
   {
        staticvoidMain(string[] args)
        {
            AsyncProcess();
            Console.Read();
        }
 
        privateasyncstaticvoidAsyncProcess()
        {
            HttpClienthttpClient=newHttpClient();
 
            //获取货品信息列表
            HttpResponseMessageresponseMessage=
                awaithttpClient.GetAsync("http://localhost/selfhost/api/product");
            IEnumerable<Product>products=awaitresponseMessage.Content.ReadAsAsync<IEnumerable<Product>>();
            OutputProductInfo(products);
 
 
            //添加货品
            Productproduct=newProduct()
            {
                ProductID="003",
                ProductName="《ASP.NET Web API 2 框架揭秘》",
                ProductCategory="食品类"
            };
            awaithttpClient.PostAsJsonAsync<Product>("http://localhost/selfhost/api/product", product);
            responseMessage=awaithttpClient.GetAsync("http://localhost/selfhost/api/product");
            products=awaitresponseMessage.Content.ReadAsAsync<IEnumerable<Product>>();
            OutputProductInfo(products);
 
            //修改指定货品信息
            responseMessage=awaithttpClient.GetAsync("http://localhost/selfhost/api/product/003");
            product= (awaitresponseMessage.Content.ReadAsAsync<IEnumerable<Product>>()).First();
            product.ProductCategory="书籍";
            awaithttpClient.PutAsJsonAsync<Product>("http://localhost/selfhost/api/product", product);
            responseMessage=awaithttpClient.GetAsync("http://localhost/selfhost/api/product");
            products=awaitresponseMessage.Content.ReadAsAsync<IEnumerable<Product>>();
            OutputProductInfo(products);
 
            //删除指定货品
            awaithttpClient.DeleteAsync("http://localhost/selfhost/api/product/001");
            responseMessage=awaithttpClient.GetAsync("http://localhost/selfhost/api/product");
            products=awaitresponseMessage.Content.ReadAsAsync<IEnumerable<Product>>();
            OutputProductInfo(products);
 
        }
 
        privatestaticvoidOutputProductInfo(IEnumerable<Product>products)
        {
            foreach (Productproductinproducts)
            {
                Console.WriteLine(
                    "ProductID:{0},ProductName:{1},ProductCategorm:{2}",
                    product.ProductID, product.ProductName, product.ProductCategory);
            }
            Console.WriteLine("—————————————————————————");
        }
   }
}

到此,关于“ASP.NET Web API示例分析”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI