ASP. 2 Lesson Nineth-Self-hosted web API

Source: Internet
Author: User

Objective

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

The ASP. NET Web API can require IIS. You can host a Web API on your own console.

This tutorial shows you 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 I have the default framework version of 4.5. Then use NuGet to download the installation Microsoft.AspNet.WebApi.SelfHost.

Creating model and Controller

First, add a public common class product.

     Public classProduct { Public intId {Get;Set; }  Public stringName {Get;Set; }  Public stringCategory {Get;Set; }  Public decimalPrice {Get;Set; } }

Then add a public common class ProductsController, and this class inherits from System.Web.Http.ApiController. Remember to add Extension reference System.Web.Http.

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Net;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Web.Http;namespaceselfhost{ 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)); }    }}

This controller defines three get methods:

Hosting the Web API

Open Program.cs, and then add the following usage statement:

using System.Web.Http; using

Of course, if you don't have a reference, you should add the reference first (plus System.Net.Http). Then add the following code to Program.cs:

varConfig =NewHttpselfhostconfiguration ("http://localhost:8080"); 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 ();}

Now you can run the console program.

It is now possible to test the correctness of the Web API simply by using URIs.

(optional) Add an HTTP URL to the namespace reservation (no problem encountered, no test pending)

This application listens for "http://localhost:8080". By default, listening for a special HTTP URL requires administrator privileges. When you run the console application above, you may get an error like this: "HTTP could 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 give your account permissions to keep this URL.

To use Netsh.exe, open a command prompt as an administrator and type the following command:

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

which Machine\username is your user account.

When you're done with self-hosting, it's best to be sure to delete this reserved URL.

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

Invoking the Web API through a client application

Let's write a simple console application to invoke the Web API.

Add a console application and name it "ClientApp".

The same is done with NuGet to add Microsoft.AspNet.WebApi.Client.

Of course, you need to apply selfhost to this project.

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

Using

To add a static httpclient instance:

namespace clientapp{    class  program    {        staticnew  HttpClient ();         staticvoid Main (string[] args)        {        }     }}

Add three methods to get all product list information, obtain the specified product information by ID, and get the product list information through the catalogue.

Static voidlistallproducts () {Httpresponsemessage resp= client. Getasync ("api/products").    Result; Resp.    Ensuresuccessstatuscode (); varProducts = resp. Content.readasasync<ienumerable<selfhost.product>>().    Result; foreach(varPinchProducts ) {Console.WriteLine ("{0} {1} {2} ({3})", P.id, P.name, P.price, p.category); }}Static voidListproduct (intID) {    varRESP = client. Getasync (string. Format ("api/products/{0}", id)).    Result; Resp.    Ensuresuccessstatuscode (); varProduct = resp. Content.readasasync<selfhost.product>().    Result; Console.WriteLine ("ID {0}: {1}", ID, product. Name);}Static voidListproducts (stringcategory) {Console.WriteLine ("Products in ' {0} ':", category); stringquery =string. Format ("api/products?category={0}", category); varRESP =client. Getasync (query).    Result; Resp.    Ensuresuccessstatuscode (); varProducts = resp. Content.readasasync<ienumerable<selfhost.product>>().    Result; foreach(varProductinchProducts ) {Console.WriteLine (product.    Name); }}

Each method follows the same pattern:

1. Call Httpclient.getasync to send an HTTP GET request to the appropriate URI.

2. Call Httpresponsemessage.ensuresuccessstatuscode , if the HTTP response status is an error code, then this method throws an exception.

3. Call readasasync<t> to deserialize a CLR type from the HTTP response. This method is an extension method that is defined in System.Net.Http.HttpContentExtensions.


Getasync and Readasasync both methods are asynchronous methods. They represent asynchronous operations by returning a Task object. get Result property blocks the thread until the operation is complete.

before you call these methods, the property on BaseAddress is set to the HttpClient instance of "http://localhost:8080". For example:

Static void Main (string[] args) {    new Uri ("http://localhost:8080" );    Listallproducts ();    Listproduct (1);    Listproducts ("toys");    Console.WriteLine ("press Enter to quit. " );    Console.ReadLine ();}

Next, Test. Set up the startup project.

To predict the output, the following should be output:

1 1.0 (groceries) 2 3.75 (Toys) 3 16.99   1in'toys': Yo-yopress Enter to quit.

Run the program to see the results

Summarize

The feeling is still relatively simple, so the step-by-step down is still no hindrance.

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

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

ASP. 2 Lesson Nineth-Self-hosted web API

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.