並添加WebApi相關引用,注意,添加以後會默認幫你添加 System.Web.Http.WebHost
的引用,不過,折並無什麼鳥用,幹掉他,而後手動添加引用 System.Web.Http.SelfHost
。web
嗯,如今咱們須要一個Controller了:api
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Http; using WebApi.SelfHosting.Demo.Models; namespace WebApi.SelfHosting.Demo.Controllers { 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 } }; /// <summary> /// [/api/products] Get a list of all products. /// </summary> /// <returns></returns> public IEnumerable<Product> GetAllProducts() { return products; } /// <summary> /// [/api/products/id] Get a product by ID. /// </summary> /// <param name="id"></param> /// <returns></returns> public Product GetProductById(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return product; } /// <summary> /// [/api/products/?category=category] Get a list of products by category. /// </summary> /// <param name="category"></param> /// <returns></returns> public IEnumerable<Product> GetProductsByCategory(string category) { return products.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)); } } }
嗯, Product
類在這裏:瀏覽器
namespace WebApi.SelfHosting.Demo.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }
嗯。。。繼續僞裝在寫一個正常的 WebApi
...安全
但是,人家是在Global裏面註冊路由的啊,我們這玩意沒有Global啊!不要緊,我們有Main函數啊,都是程序入口,應該差很少,呵呵。。。服務器
using System; using System.Web.Http; using System.Web.Http.SelfHost; namespace WebApi.SelfHosting.Demo { class Program { static void Main(string[] args) { 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("Server Listening at 8080..."); Console.WriteLine("Press Enter to quit."); Console.ReadLine(); } } } }
注意:函數
HttpConfiguration
裏的,可是基於SelfHost的倒是註冊到 HttpSelfHostConfiguration
: 看吧,很明顯,多了個SelfHost補充: 有人表示編譯的時候會報下面的異常:ui
類型「System.Web.Http.SelfHost.HttpSelfHostConfiguration」違反了繼承安全性規則。派生類型必須與基類型的安全可訪問性匹配或者比基類型的安全可訪問性低。搜索引擎
搜索引擎給出的解決方法是修改 AssemblyInfo.cs
文件,手動指定程序集的透明級別。spa
其實並非:多半是由於你引用的 System.Web.Http.SelfHost
程序集與你添加的WebApi版本不符形成的 code