The ASP. NET Web API does not require IIS and can be implemented directly using a console program.
First, create a new console program, the project is named Hostapi
Ii. Setting the target framework for the. NET Framework 4
Third, NuGet Add Reference Microsoft.AspNet.WebApi.SelfHost
Iv. Adding a Product model class
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacehostapi{ Public classProduct { Public intId {Get;Set; } Public stringName {Get;Set; } Public stringCategory {Get;Set; } Public decimalPrice {Get;Set; } }}
Five, add a ProductsController
public class named. derive this class from System.Web.Http.ApiController .
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Web.Http;namespacehostapi{ Public classProductscontroller:apicontroller {product[] products=Newproduct[] {NewProduct {Id =1, Name ="Tomato Soup", Category ="Groceries", Price =1 }, NewProduct {Id =2, Name ="Yo-Yo", Category ="Toys", Price =3.75M }, NewProduct {Id =3, Name ="Hammer", Category ="Hardware", Price =16.99M } }; PublicIenumerable<product>getallproducts () {returnProducts ; } PublicProduct Getproductbyid (intID) {varProduct = products. FirstOrDefault (p) = P.id = =ID); if(Product = =NULL) { Throw Newhttpresponseexception (Httpstatuscode.notfound); } returnproduct; } PublicIenumerable<product> getProductsByCategory (stringcategory) { returnProducts. Where (p =string. Equals (P.category, Category, stringcomparison.ordinalignorecase)); } }}
Vi. managed Web API
Open the Program.cs file and add the following usage statement:
using System.Web.Http; using System.Web.Http.SelfHost;
Seven, modify the Main method
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Web.Http;usingSystem.Web.Http.SelfHost; namespacehostapi{classProgram {Static voidMain (string[] args) { varConfig =NewHttpselfhostconfiguration ("http://localhost:1234"); Config. Routes.maphttproute ("API Default","Api/{controller}/{id}", New{id =routeparameter.optional}); using(Httpselfhostserver server =Newhttpselfhostserver (config)) {Server. OpenAsync (). Wait (); Console.WriteLine ("Press Enter to quit."); Console.ReadLine (); } } }}
Run directly F5 and then open the browser to access:
Get all data http://localhost:1234/api/products
Get data in the code of 1 HTTP://LOCALHOST:1234/API/PRODUCTS/1
Querying the category= data http://localhost:1234/api/products?category=Groceries
Return:
Reference Http://www.asp.net/web-api/overview/older-versions/self-host-a-web-api
Self-host Web API Learning Notes