Original reference:
ASP. NET Web API 2.2:create a self-hosted owin-based Web API from Scratch
New console program, introducing Owin Package
Pm> Install-package Microsoft.aspnet.webapi.owinselfhost-pre
Add Startup Class
Public classStartup { Public voidConfiguration (Iappbuilder app) {varWebapiconfiguration =Configurewebapi (); //Use the extension method provided by the Webapi.owin library:app. Usewebapi (webapiconfiguration); } Privatehttpconfiguration Configurewebapi () {varConfig =Newhttpconfiguration (); Config. Routes.maphttproute ("Defaultapi", "Api/{controller}/{id}", New{id =routeparameter.optional}); returnconfig; } }
Add Models,Controllers folder, add Company, Companiescontroller
Public class company { [Key] publicintgetset;} Public string Get Set ; } }
Public classCompaniescontroller:apicontroller {applicationdbcontext _db=NewApplicationdbcontext (); PublicIenumerable<company>Get () {return_db.companies; } Public AsyncTask<company> Get (intID) {varCompany =await_db.companies.firstordefaultasync (c = c.id = =ID); if(Company = =NULL) { Throw Newhttpresponseexception (System.Net.HttpStatusCode.NotFound); } returnCompany ; } Public AsyncTask<ihttpactionresult>Post (company company) {if(Company = =NULL) { returnBadrequest ("Argument Null"); } varCompanyexists =await_db.companies.anyasync (c = c.id = =Company . ID); if(companyexists) {returnBadrequest ("Exists"); } _db.companies.add (company); await_db.savechangesasync (); returnOk (); } Public AsyncTask<ihttpactionresult>Put (company company) {if(Company = =NULL) { returnBadrequest ("Argument Null"); } varexisting =await_db.companies.firstordefaultasync (c = c.id = =Company . ID); if(Existing = =NULL) { returnNotFound (); } existing. Name=Company . Name; await_db.savechangesasync (); returnOk (); } Public AsyncTask<ihttpactionresult> Delete (intID) {varCompany =await_db.companies.firstordefaultasync (c = c.id = =ID); if(Company = =NULL) { returnNotFound (); } _db.companies.remove (company); await_db.savechangesasync (); returnOk (); } }
View Code
Add EntityFramework package, add Applicationdbcontext
namespaceconsolewebapi.models{ Public classApplicationdbcontext:dbcontext { PublicApplicationdbcontext ():Base("MyDatabase") { } PublicIdbset<company> Companies {Get;Set; } } Public classApplicationdbinitializer:dropcreatedatabasealways<applicationdbcontext> { protected Override voidSeed (Applicationdbcontext context) {Base. Seed (context); CONTEXT.COMPANIES.ADD (NewCompany {Name ="Microsoft" }); CONTEXT.COMPANIES.ADD (NewCompany {Name ="Google" }); CONTEXT.COMPANIES.ADD (NewCompany {Name ="Apple" }); } }}
View Code
Add a connection string in app. Config
<connectionStrings> <add name="MyDatabase" connectionstring= " Data Source=.;i Nitial catalog=test;integrated security=true; Connect timeout=15; Encrypt=false; Trustservercertificate=true; Applicationintent=readwrite; Multisubnetfailover=false "providername="System.Data.SqlClient"/> </connectionStrings>
View Code
Add code to the entry main
Static voidMain (string[] args) {Console.WriteLine ("Initializing and Seeding database ..."); Database.setinitializer (NewApplicationdbinitializer ()); vardb =NewApplicationdbcontext (); intCount =Db.Companies.Count (); Console.WriteLine ("Initializing and seeding database with {0} company records ...", Count); stringBaseUri ="http://localhost:8080"; Console.WriteLine ("starting web Server ..."); Webapp.start<Startup>(BaseUri); Console.WriteLine ("Server running at {0}-press Enter to quit.", BaseUri); Console.ReadLine (); }
View Code
Start the program, open HTTP://LOCALHOST:8080/API/COMPANIES/1
You can see the results.
Using the console program to build Webapi