Using the console program to build Webapi

Source: Internet
Author: User
Tags baseuri connectionstrings

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.