Asp. Net Web API (6), asp. netwebapi

Source: Internet
Author: User

Asp. Net Web API (6), asp. netwebapi

IIS is not required for Asp. Net Web APIs. You can host a Web API on the host.

Create a WebAPI. Server project

Create a controller Project Server

 

Add in NugetMicrosoft. AspNet. WebApi. SelfHost

Create Model and Controller

First, add a Product type on the server.

namespace WebAPI.Server.Models{    public class Product    {        public int Id { get; set; }        public string Name { get; set; }        public string Category { get; set; }        public decimal Price { get; set; }    }}

Then add a ProductController controller, which inherits fromSytem. Web. Http. ApiController. Remember to extend referenceSystem. Web. Http

Using System. collections. generic; using System. linq; using System. net; using System. web. http; using WebAPI. server. models; namespace WebAPI. server. controller {public class ProductController: ApiController {private static IList <Product> products; static ProductController () {products = new List <Product> (); products. add (new Product {Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1}); products. add (new Product {Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75 M}); products. add (new Product {Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99 M });} /// <summary> /// obtain all items /// </summary> /// <returns> </returns> public IEnumerable <Product> GetProducts () {return products ;} /// <summary> /// obtain the product /// </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> /// add product /// </summary> /// <param name = "Product"> </param> public void PostProduct (product) {products. add (product );} /// <summary> /// modify the product /// </summary> /// <param name = "id"> </param> /// <param name = "product"> </param> public void PutProduct (int id, product product) {var pro = products. singleOrDefault (y => y. id = id); pro. category = product. category; pro. name = product. name; pro. price = product. price ;} /// <summary> /// Delete the product /// </summary> /// <param name = "id"> </param> public void DeleteProduct (int id) {products. remove (products. singleOrDefault (y => y. id = id ));}}}

 

Carry Web API

Add the following reference to the Program class:

using System.Http;using System.Web.Http.SelfHost;

Then add the following code:

Using System; using System. web. http; using System. web. http. selfHost; namespace WebAPI. server {class Program {static void Main (string [] args) {// create an HTTP service configuration class var config = new HttpSelfHostConfiguration ("http: // localhost: 7777 "); config. routes. mapHttpRoute ("API Default", "api/{Controller}/{id}", new {id = RouteParameter. optional}); // create a System. web. http implementation class using (HttpSelfHostServer server = new HttpSelfHostServer (config) {server. openAsync (). wait (); Console. writeLine ("server enabled"); Console. read ();}}}}

This application listens for "http: // localhost: 7777 ". By default, administrators are required to listen for a special http url. When running the above application, you may get the following error: "HTTP cocould not register URL http: // +: 7777". There are two ways to avoid this error:

1. Run Visual Studio as an administrator.

2.use netsh.exe to reserve this URL for your account.

To use netsh.exe, open the command prompt box as an administrator and enter the following command:

netsh http add urlacl url=http://+:7777/ user=machine\username

WhereMachine \ usernameIs your user account.

When using self-managed services, it is best to delete the reserved URL.

netsh http delete urlacl url=http://+:7777/

Then start the server

 

Create a WebAPI. Client Project

Create a console project client

Add in NugetMicrosoft. AspNet. WebApi. Client

Add Model

Add an entity model of Product with the same attributes as the server in the client.

namespace WebAPI.Client.Models{    class Product    {        public int Id { get; set; }        public string Name { get; set; }        public string Category { get; set; }        public decimal Price { get; set; }    }}
Create HttpClient helper class
Using System; using System. collections. generic; using System. linq; using System. net. http; using System. text; using System. threading. tasks; using WebAPI. client. models; namespace WebAPI. client {public class MyHtppClient {HttpClient client; public MyHtppClient (String uri) {// initialize client = new HttpClient (); Client. baseAddress = new Uri (uri); // Add an item to the request header. Client. defaultRequestHeaders. accept. add (new System. net. http. headers. mediaTypeWithQualityHeaderValue ("application/json") ;}/// <summary> /// get all items /// </summary> public void GetAll () {// obtain HttpResponseMessage message = client. getAsync ("api/product "). result; if (message. isSuccessStatusCode) {// success returns var produsts = message. content. readAsAsync <IEnumerable <Product> (). result; foreach (var item in produsts) {Console. writeLine ($ "item No.: {item. id}; item Name: {item. name}; item price: {item. price}; item type: {item. category} ") ;}} public void GetbyId (int id) {HttpResponseMessage message = client. getAsync ($ "api/product/{id }"). result; if (message. isSuccessStatusCode) {var product = message. content. readAsAsync <Product> (). result; Console. writeLine ($ "product No.: {product. id}; Item Name: {product. name}; product price: {product. price}; item type: {product. category} ") ;}} public void Add (Product product) {HttpResponseMessage message = client. postAsJsonAsync ("api/product", product ). result; Console. writeLine ("{0} ({1})", (int) message. statusCode, message. reasonPhrase);} public void Modify (int id, Product product) {HttpResponseMessage = client. putAsJsonAsync ($ "api/product/{id}", product ). result; Console. writeLine ("{0} ({1})", (int) message. statusCode, message. reasonPhrase);} public void Delete (int id) {HttpResponseMessage message = client. deleteAsync ($ "api/product/{id }"). result; Console. writeLine ("{0} ({1})", (int) message. statusCode, message. reasonPhrase );}}}

Then we test all the methods in the main method.

namespace WebAPI.Client{    class Program    {        static void Main(string[] args)        {            MyHtppClient myHtppClient = new MyHtppClient("http://localhost:7777");            myHtppClient.GetAll();        }    }}

Other methods will not be tested here

Configure HttpClient

To configure HttpClient, create a WebRequestHandler instance, set its properties, and pass it to the HttpClient constructor.

WebRequestHandler handler = new WebRequestHandler(){    AllowAutoRedirect = false,    UseProxy = false };HttpClient client = new HttpClient(handler);

WebRequestHandlerSlaveHttpMessageHandler. You can alsoHttpMessageHandlerDerived and inserted into the custom message processing program

Related Article

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.