"The unveiling of the ASP. NET Web API2 framework" first knowledge web API

Source: Internet
Author: User
Tags webhost

What is the Web Api?

The MSDN:ASP.NET Web API is a framework for easily building HTTP services that can access multiple clients, including browsers and mobile devices

Baidu Encyclopedia: Web API is a network application interface.

Personal understanding: The Web API is provided to a variety of clients on the data to do crud (delete and change) operation of the unified interface

-------------------------------------------

The ASP. NET Web API supports multiple boarding methods

1,iis as the host (Creating an ASP. NET Web application as a host for the web API)

2, self-hosted (no IIS support required, use any application as host "console, Windows Forms, WPF, even Windows Service")

read a section of the Artech great God Web API, record what you learned

[Build a simple web API]

1. Host Web API in Web host mode

Visual Studio provides us with a project template dedicated to creating an ASP. NET Web API app, and we can create a full Aps.net Web API project one-click.

This is not created automatically with Visual Studio first. We are completely writing our program in the empty project we created.

1.1 Building Solutions

    • API: An empty class library project that behaves as a Httpcontroller type of Web API is defined in this project
    • Model: An empty class Library project, where entity classes are defined
    • Webhost: An empty ASP. NET Web Application

1.2 Defining the Web API

Before we formally define the Web API, we need to define an entity class in the project model that represents the contact, and here is a simple definition.

    public class "Contact"    {public        string ID {get; set;}        public string Name {get; set;}        public string Phonenum {get;set;}           }

The Web API definition in the API project needs to inherit the Apicontroller,apicontroller definition in the assembly "System.Web.Http.dll", the assembly in "C:\Program Files (x86) \micro Soft asp.net\asp.net Web Stack 5\packages\microsoft.aspnet.webapi.core.5.0.0\lib\net45 "can be found

 public class Contactscontroller:apicontroller {list<contact> contacts;            Public Contactscontroller () {contacts = new list<contact> (); Contacts.            ADD (New Contact () {ID = "001", Name = "small white", Phonenum = "13529093839"}); Contacts.            ADD (New Contact () {ID = "002", Name = "White", Phonenum = "13529093838"}); Contacts.        ADD (New Contact () {ID = "003", Name = "small Black", Phonenum = "13529088838"}); Ienumerable<contact> Get (String id=null) {return from C in Contacts W Here c.id==id| | String.                IsNullOrEmpty (ID) select C; public void Post (contact item) {Contacts.        ADD (item); The public void is Put (contact item) {Contacts. Remove (Contacts.            First (c = c.id = = item.id)); Contacts.        ADD (item); } public void Delete (string id) {Contacts. Remove (Contacts. First (c + = c.ID = = ID)); }    }

1.3 Hosting webhost as a Web API

Webhost in the solution is an empty ASP. NET Web application, we also need to add some necessary assembly references for it.

    • System.Web.Http; (\microsoft.aspnet.webapi.core.5.0.0\lib\net45)
    • System.Web.Http.WebHost; (\microsoft.aspnet.webapi.webhost.5.0.0\lib\net45)
    • System.Net.Http;
    • System.Net.Http.Formatting; (\microsoft.aspnet.webapi.client.5.0.0\lib\net45)

We need to add a Global.asax global profile to the Webhost project, register a default route, and the routing system will resolve the name of the target Httpcontroller and action that the current request accesses

        protected void Application_Start (object sender, EventArgs e)        {            GlobalConfiguration.Configuration.Routes.MapHttpRoute (                name: "Default",                routetemplate: "Api/{controller} /{id} ",                defaults:new {id = routeparameter.optional}                );        }

  There is no route parameter in the routing rule that represents the target action, how does the ASP. NET WEB API determine which action method should be called based on the request? In fact, it can use the HTTP method to determine the target action method according to the request. Of course, it is also supported to provide the route parameter ({action}) that represents the action name in the registration routing template.

Now that the Web API's webhost-hosted work is done, we can use the browser to invoke the hosted Web API to determine the success of the boarding process. Because the browser accesses the address we entered in the Address bar by default, it always takes the http-get request, so we can only use it to invoke the action method that supports Http-get, which is the Get method defined in Contactscontroller.

With chrome, you can see that the list of contacts we get is a data representation in XML format, and for the ASP, it takes precedence over the type of media that the request header "Accept" uses to determine the presentation of the corresponding content application.

As shown below is the content that Chrome accesses "http://localhost:3697/api/contacts/001" to send the request, and it gets the response in XML because the "Accept" header specifies a list of media types that only " Application/xml "is supported by the ASP. If we use IE, the request's "Accept" header will carry a different list of media types, and we will actually get a response in JSON format

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8accept-encoding:gzip, deflate, Sdchaccept-language:zh-cn,zh;q=0.8cache-control:max-age=0host:localhost:3697proxy-connection: keep-aliveuser-agent:mozilla/5.0 (Windows NT 6.3; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/41.0.2272.89 safari/537.36

We use fiddler to send HTTP requests that invoke the Web API to get the result of the response in JSON format.

, Fiddler sent a http-get request for the destination address "http://localhost:3697/api/contacts/001" and added a "Accept" header with a value of "Application/json" , execute sends a request and does get a list of contacts in JSON format

Enable IIS to support put and delete requests

When defining Contactscontroller, we use GET, Post, Put, delete as the HTTP methods supported for getting, creating, modifying, and deleting contacts. However, IIS does not support the put and delete requests by default

IIS rejects put and delete requests as a result of a custom HttpModule named "Webdavmodule" that is registered by default. The most straightforward way to solve this problem is to remove the registered HttpModule

<system.webServer>    <modules runallmanagedmodulesforallrequests= "true" >      <remove name= " Webdavmodule "/>    </modules></system.webServer>

2, self-hosted way hosted web API

We add an empty console application Selfhost as the host in the original solution

As with webhost, referencing API.dll in a solution also requires the application of some required assemblies (red is different from webhost)

    • System.Web.Http; (\microsoft.aspnet.webapi.core.5.0.0\lib\net45)
    • System.Web.Http.SelfHost; (\microsoft.aspnet.webapi.selfhost.5.0.0\lib\net45)
    • System.Net.Http;
    • System.Net.Http.Formatting; (\microsoft.aspnet.webapi.client.5.0.0\lib\net45)

Through the previous webhost, we know that the next thing to do is to register the route. Prior to this we also needed to dynamically load the assembly API.dll in the solution,

here is the Artech great god in " create an ASP. NET Web API 2.0 application on an empty ASP. "Write in the Error Place Httpserver.openasync () after the Wait () method is not executed, cause the computer is not assigned a port to the program, which makes me a long time, but also learned other knowledge, such as: [ How to see the computer a port by who occupy]

        static void Main (string[] args)        {                       assembly.load ("Api,version=1.0.0.0,culture=neutral,publickeytoken=null" );            Httpselfhostconfiguration configuration = new Httpselfhostconfiguration ("http://127.0.0.1:7304");            using (httpselfhostserver httpserver = new Httpselfhostserver (configuration))            {                HttpServer.Configuration.Routes.MapHttpRoute (                    name: "Defaultapi",                    routetemplate: "Api/{controller}/{id}" ,                    defaults:new {id = routeparameter.optional});                Httpserver.openasync ();//Correction: Httpserver.openasync (). Wait ();                Console.read ();            }        }

When we do not execute the Wait () method, check to see if the computer has an assigned port

1, first bring up the command window: start----> Run---->cmd, or the WINDOW+R key combination

2, enter command: Netstat-ano, you can see the situation of all ports. I found hundreds of times and I couldn't find the 7304 port.

If you add wait (), the runtime appears after the

"HTTP cannot register URL http://+:* ***/. The process does not have access to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for more information) "

You just have to open Visual Studio as an administrator.

"The unveiling of the ASP. NET Web API2 framework" first knowledge 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.