Asp. Net Web API 2 Lesson 9-Self-hosting Web API, asp. netapi

Source: Internet
Author: User

Asp. Net Web API 2 Lesson 9-Self-hosting Web API, asp. netapi

Preface

Before reading this article, you can also go to the Asp. Net Web API 2 series navigation to view http://www.cnblogs.com/aehyok/p/3446289.html

Asp. Net Web APIs can require IIS. You can host a Web API on your host.

This tutorial shows how to host a Web API in a console application. The development tool used is VS2013.

This article sample code download link http://pan.baidu.com/s/1d56zf

Create a console application

 

Here, the default Framework version is 4.5. Then download and install Microsoft. AspNet. WebApi. SelfHost through Nuget.

Create Model and Controller

First, add a public class Product.

    public class Product    {        public int Id { get; set; }        public string Name { get; set; }        public string Category { get; set; }        public decimal Price { get; set; }    }

Add a public class ProductsController, and the class inherits fromSystem. Web. Http. ApiController. Remember to add extension referenceSystem. Web. Http.

using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Text;using System.Threading.Tasks;using System.Web.Http;namespace SelfHost{    public class ProductsController:ApiController    {        Product[] products = new Product[]          {              new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },              new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },              new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }          };        public IEnumerable<Product> GetAllProducts()        {            return products;        }        public Product GetProductById(int id)        {            var product = products.FirstOrDefault((p) => p.Id == id);            if (product == null)            {                throw new HttpResponseException(HttpStatusCode.NotFound);            }            return product;        }        public IEnumerable<Product> GetProductsByCategory(string category)        {            return products.Where(p => string.Equals(p.Category, category,                    StringComparison.OrdinalIgnoreCase));        }    }}

This controller defines three Get methods:

Carry Web API

Open Program. cs and add the following statement:

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

Of course, if you do not have a reference, you must add the reference first (there are alsoSystem. Net. Http). Then add the following code to Program. cs:

var config = new HttpSelfHostConfiguration("http://localhost:8080");config.Routes.MapHttpRoute(    "API Default", "api/{controller}/{id}",     new { id = RouteParameter.Optional });using (HttpSelfHostServer server = new HttpSelfHostServer(config)){    server.OpenAsync().Wait();    Console.WriteLine("Press Enter to quit.");    Console.ReadLine();}

Now you can run the console program.

Now we can use URI to test the correctness of Web APIs.

(Optional) add an http url namespace to keep it (this problem is not encountered and is not tested yet)

This application listens to "http: // localhost: 8080 ". By default, administrators are required to listen for a special http url. When you run the preceding console application, you may get the following error: "HTTP cocould not register URL http: // +: 8080 ", 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://+:8080/ 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://+:8080/

Call Web APIs through client applications

Let's write a simple console application to call Web APIs.

Add a console application and name it "ClientApp ".

Similarly, Microsoft. AspNet. WebApi. Client is added through Nuget.

 

Of course, you also need to apply the SelfHost project.

Open the ClientApp project's Program. cs file and add the following using statement

using System.Net.Http; 

Add a static HttpClient instance:

namespace ClientApp{    class Program    {        static HttpClient client = new HttpClient();        static void Main(string[] args)        {        }    }}

Add three methods to obtain the list of all products, get the specified product information by ID, and get the product list information by directory.

static void ListAllProducts(){    HttpResponseMessage resp = client.GetAsync("api/products").Result;    resp.EnsureSuccessStatusCode();    var products = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Product>>().Result;    foreach (var p in products)    {        Console.WriteLine("{0} {1} {2} ({3})", p.Id, p.Name, p.Price, p.Category);    }}static void ListProduct(int id){    var resp = client.GetAsync(string.Format("api/products/{0}", id)).Result;    resp.EnsureSuccessStatusCode();    var product = resp.Content.ReadAsAsync<SelfHost.Product>().Result;    Console.WriteLine("ID {0}: {1}", id, product.Name);}static void ListProducts(string category){    Console.WriteLine("Products in '{0}':", category);    string query = string.Format("api/products?category={0}", category);    var resp = client.GetAsync(query).Result;    resp.EnsureSuccessStatusCode();    var products = resp.Content.ReadAsAsync<IEnumerable<SelfHost.Product>>().Result;    foreach (var product in products)    {        Console.WriteLine(product.Name);    }}

Each method follows the same pattern:

1. CallHttpClient. GetAsyncTo send an HTTP Get request to the appropriate URI.

2. CallHttpResponseMessage. EnsureSuccessStatusCodeIf the HTTP response status is an error code, this method throws an exception.

3. CallReadAsAsync <T>Deserializes a clr type from an HTTP response. This method is an extension method, which is defined inSystem. Net. Http. HttpContentExtensions.


GetAsyncAndReadAsAsyncBoth methods are asynchronous. They returnTaskObject To represent asynchronous operations. ObtainResultAttribute to stop the thread until the operation is completed.

Before calling these methods, set the attribute on BaseAddress to the HttpClient instance of "http: // localhost: 8080. For example:

 

static void Main(string[] args){    client.BaseAddress = new Uri("http://localhost:8080");    ListAllProducts();    ListProduct(1);    ListProducts("toys");    Console.WriteLine("Press Enter to quit.");    Console.ReadLine();}

Next, perform the test. Set the startup project.

The prediction output should output the following content:

1 Tomato Soup 1.0 (Groceries)2 Yo-yo 3.75 (Toys)3 Hammer 16.99 (Hardware)ID 1: Tomato SoupProducts in 'toys':Yo-yoPress Enter to quit.

Run the program and view the result

Summary

It seems to be relatively simple, so there is no obstacle to step by step.

Reference link http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api for this article

This article has been synced to the Web API series navigation http://www.cnblogs.com/aehyok/p/3446289.html

This article sample code download link http://pan.baidu.com/s/1d56zf

Reference page:

Http://www.yuanjiaocheng.net/webapi/action-method-returntype.html

Http://www.yuanjiaocheng.net/webapi/web-api-reqresq-format.html

Http://www.yuanjiaocheng.net/webapi/media-formatter.html

Http://www.yuanjiaocheng.net/webapi/webapi-filters.html

Http://www.yuanjiaocheng.net/webapi/create-crud-api-1.html

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.