標籤:create url hosting filters 提示 需要 itblog 異常 分享
前言
閱讀本文之前,您也可以到Asp.Net Web API 2 系列導航進行查看 http://www.cnblogs.com/aehyok/p/3446289.html
Asp.Net Web API可以需要IIS。你可以在你自己的主機上來承載一個Web API。
本教程來展示在控制台應用程式中來承載一個Web API。使用的開發工具為VS2013。
本文範例程式碼下載連結http://pan.baidu.com/s/1d56zf
建立一個控制台應用程式
這裡我預設的Framework版本為4.5的。然後通過Nuget來下載安裝Microsoft.AspNet.WebApi.SelfHost。
建立Model和Controller
首先添加一個public公用類Product。
public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } }
然後添加一個public公用類ProductsController,並且這個類繼承自System.Web.Http.ApiController。記得添加擴充引用System.Web.Http。
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Text;using System.Threading.Tasks;using System.Web.Http;namespace SelfHost{ public class ProductsController:ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; public IEnumerable<Product> GetAllProducts() { return products; } public Product GetProductById(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return product; } public IEnumerable<Product> GetProductsByCategory(string category) { return products.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)); } }}
這個控制器定義了三個Get方法:
承載Web API
開啟Program.cs,然後添加如下使用語句:
using System.Web.Http;using System.Web.Http.SelfHost;
當然如果你沒有引用,還是先要添加引用的(另外還有System.Net.Http)。然後添加如下代碼到Program.cs裡:
var config = new HttpSelfHostConfiguration("http://localhost:8080");config.Routes.MapHttpRoute( "API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });using (HttpSelfHostServer server = new HttpSelfHostServer(config)){ server.OpenAsync().Wait(); Console.WriteLine("Press Enter to quit."); Console.ReadLine();}
現在你可以運行控制台程式了。
現在可以通過URI來簡單測試Web API的正確性。
(可選的)添加一個HTTP URL命名空間保留(沒遇到這個問題,暫未測試)
這個應用程式偵聽到"http://localhost:8080"。在預設情況下,偵聽一個特殊的HTTP URL是需要管理員權限的。當你運行上面的控制台應用程式的時候,你可能會得到這樣的一個錯誤:"HTTP could not register URL http://+:8080",這兒有兩種方式去避免這個錯誤:
1.以管理員身份運行Visual Studio。
2.使用Netsh.exe給與你的帳號許可權去保留這個URL。
若要使用Netsh.exe,以管理員身份開啟命令提示框,並鍵入以下命令:
netsh http add urlacl url=http://+:8080/ user=machine\username
其中machine\username是您的使用者帳戶。
當你使用完自託管的時候,最好是確定刪除這個保留的URL。
netsh http delete urlacl url=http://+:8080/
通過用戶端應用程式來調用Web API
讓我們來寫一個簡單的控制台應用程式來調用Web API。
添加一個控制台應用程式,並命名為"ClientApp"。
同樣的通過Nuget來添加Microsoft.AspNet.WebApi.Client。
當然還需要應用SelfHost這個項目。
開啟ClientApp項目的Program.cs檔案,添加如下using語句
using System.Net.Http;
添加一個靜態HttpClient執行個體:
namespace ClientApp{ class Program { static HttpClient client = new HttpClient(); static void Main(string[] args) { } }}
添加三個方法 獲得所有產品列表資訊,通過ID獲得指定產品資訊,通過目錄獲得產品列表資訊。
static void ListAllProducts(){ HttpResponseMessage resp = client.GetAsync("api/products").Result; resp.EnsureSuccessStatusCode(); var products = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Product>>().Result; foreach (var p in products) { Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Price, p.Category); }}static void ListProduct(int id){ var resp = client.GetAsync(string.Format("api/products/{0}", id)).Result; resp.EnsureSuccessStatusCode(); var product = resp.Content.ReadAsAsync<SelfHost.Product>().Result; Console.WriteLine("ID {0}: {1}", id, product.Name);}static void ListProducts(string category){ Console.WriteLine("Products in ‘{0}‘:", category); string query = string.Format("api/products?category={0}", category); var resp = client.GetAsync(query).Result; resp.EnsureSuccessStatusCode(); var products = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Product>>().Result; foreach (var product in products) { Console.WriteLine(product.Name); }}
每個方法遵循相同的模式:
1.調用HttpClient.GetAsync來發送一個HTTP Get請求到適當的URI。
2.調用HttpResponseMessage.EnsureSuccessStatusCode ,如果HTTP響應狀態是一個錯誤碼,那麼這個方法將拋出一個異常。
3.調用ReadAsAsync<T> 還原序列化一個來自HTTP響應的CLR類型。 這個方法是一個擴充方法,被定義在System.Net.Http.HttpContentExtensions。
GetAsync 和ReadAsAsync 這兩個方法都是非同步方法呼叫。它們通過返回Task 對象來代表非同步作業。擷取Result屬性阻止線程,直到操作完成。
在調用這些方法之前, BaseAddress 上的屬性設定為"http://localhost:8080"的 HttpClient 執行個體。例如:
static void Main(string[] args){ client.BaseAddress = new Uri("http://localhost:8080"); ListAllProducts(); ListProduct(1); ListProducts("toys"); Console.WriteLine("Press Enter to quit."); Console.ReadLine();}
接下來,進行測試。設定啟動項目。
預測輸出內容,應該會輸出以下內容:
1 Tomato Soup 1.0 (Groceries)2 Yo-yo 3.75 (Toys)3 Hammer 16.99 (Hardware)ID 1: Tomato SoupProducts in ‘toys‘:Yo-yoPress Enter to quit.
運行程式,查看結果
總結
感覺還是比較簡單的吧,就這樣一步一步的下來還是沒什麼阻礙的。
本文的參考連結http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api
本文已同步到Web API系列導航 http://www.cnblogs.com/aehyok/p/3446289.html
本文範例程式碼下載連結http://pan.baidu.com/s/1d56zf
參考頁面:
http://www.yuanjiaocheng.net/webapi/action-method-returntype.html
http://www.yuanjiaocheng.net/webapi/web-api-reqresq-format.html
http://www.yuanjiaocheng.net/webapi/media-formatter.html
http://www.yuanjiaocheng.net/webapi/webapi-filters.html
http://www.yuanjiaocheng.net/webapi/create-crud-api-1.html
Asp.Net Web API 2第九課——自承載Web API