Self-host Web API Learning Notes

Source: Internet
Author: User

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

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.