Host ASP. WebApi in Owin

Source: Internet
Author: User

What is Owin

Owin is actually a set of specifications that Microsoft has developed to understand the dependencies of the. Net Web App on IIS, which defines the interface between Web server and the Web app, so that the Web app can host the web in all compatible Owin specifications Server (contains console apps and Windows services ... )。 Specifically, Owin divides the Web app and Web server into the following modules as a whole.

Host

According to the official explanation, host refers to the process that the server and application rely on to execute. Primarily responsible for application startup and configuration.

Server

The server is responsible for HTTP communication with the client directly, and then translates the request into Owin semantics, and then uses the Owin process to process the HTTP server.

Middleware

Middleware is a module (similar to the module in IIS) that a developer registers itself with in the Owin processing request pipeline, and can participate directly in the processing of the request. So I think the Web API framework belongs to middleware. (But the official Web API framework belongs to the web framework.) It translates the semantics of owin into the semantics inside the web framework, and then processes the request according to the internal processing flow)

Application

Application is an application layer built on all of the above middleware (exactly what should be the web framework, which appears to be an official definition of a Web framework module that is meaningful).

These definitions are just a few descriptions, and how is the implementation implemented? Microsoft itself has an open source project called Katana, it is the official implementation of the Owin specification (in fact, mainly to achieve the above host/server part, because the middleware,application part of the needs of our own development). By using Katana, we deploy the Web API in a console process to see exactly how to use it and what the Owin interface is.

Host WebApi in Console App

1. First we create a console application

2. We then introduced the package Microsoft.AspNet.WebApi.OwinSelfHost through NuGet, and all the dependencies of the Owin and Web APIs in the installation process are installed.

3. We can add a apicontroller:personcontroller and add an interface method:

1[Routeprefix ("api/persons")]2      Public classPersoncontroller:apicontroller3     {4[Route ("{id}/name")]6          Public stringGetName (stringID)7         {8             returnID +"@boss";9         }Ten}

4. Next we need to configure and deploy the Web API. The Katana is on the debut.

First, in accordance with the Owin convention we have to add a class for startup, which requires a method that is signed as a configuration (Iappbuilder app):

 Public class startup{        publicvoid  Configuration (iappbuilder appBuilder)        {var  New  httpconfiguration ();            Configuration. Maphttpattributeroutes ();//Configure the Web API Router            appbuilder.usewebapi (config);//This extension is made by the package Microsoft.AspNet.WebApi.Owin provides, it is responsible for registering the Web API into the Owin processing pipeline,
and convert Owin semantics to semantics in the Web API when processing requests }}

Let's add the following code to the main function:

Webapp.start<startup> ("http://localhost:8088/");// WebApp uses the Owinhttplistener implemented by Katana to listen for HTTP requests at the specified URL. Console.WriteLine ("started! " ); Console.readkey ();

This enables us to run the Web API in the console app based on Katana.

F5 run the following to see the effect.

Then you can access the Http://localhost:8088/api/persons/123/name through the browser, you should be able to see the following screen

ADD Authenticate middleware

Next we add a protection mechanism (authentication) to the Web API by adding Owin middleware. Before I do that, I'll explain the basics of middleware.

Middleware is a set of modules that Owin server will call in turn when processing HTTP requests, and they are registered by invoking the use extension method of Iappbuilder. The middleware of the runtime are called in the same order as the registration order.

And the next middleware call to the pipeline is executed by the currently executing middleware. Specifically to the interface is this:

1. Owin defines a middleware execution interface Func<idictionary<string,object>,task>, and then requires the definition of each middleware to meet the following conditions:

    • Provides a constructor that accepts a type of execution interface type (func<idictionary<string,object>,task>)
    • Provides a method that satisfies the following signature task Invoke (idictionary<string,object> parameters)

That is, owin each middleware is finally abstracted into a function that takes IDictionary as a parameter and returns a task that performs a specific processing.

2. Owin When you create an instance of each middleware, the execution interface of the next middleware in the execution pipeline is passed in according to the registration order middleware. Middleware need to be stored up for subsequent calls.

3. When the request is processed, the server invokes the first middleware's Invoke method in the pipeline, and the middleware determines whether the next middleware is invoked after the request is processed. When invoking invoke, the Owin server

All the context properties of the current request are passed into the Dictionary object. See the official documentation for a detailed list of contextual properties.

We create a new authenticatemiddleware in the current project with the following code:

 Public classauthenticatemiddleware{Privatefunc<idictionary<string,Object, task>Nextappfunc;  PublicAuthenticatemiddleware (func<idictionary<string,Object, task>Nextmiddlewarefunc) {Nextappfunc=Nextmiddlewarefunc; }         Public AsyncTask Invoke (idictionary<string,Object>parameters) {Console.WriteLine ("authenticating"); stringqueryString = parameters["Owin. Requestquerystring"] as string;//Get the query string for the HTTP requestvarRespstream = parameters["Owin. Responsebody"] asstream;//get HTTP request for response StreamvarStreamWriter =NewStreamWriter (Respstream); varQuerydic =parsequerystring (queryString); Const stringTokenkey ="token"; Const stringPredefinetoken ="88888888"; if(!querydic.containskey (tokenkey) | | querydic[tokenkey]!=Predefinetoken)//Check if the token in the request is legal, this is only required for testing, directly hard-coded. {
If token is illegal, it is written directly to access denied to response. Stop continuing execution of other middleware in the pipeline. Streamwriter.writeline ("Access denied!"); StreamWriter.Flush (); return; }
       varIdentity =NewGenericIdentity ("boss Zhang"); parameters["server. User"] =NewGenericPrincipal (Identity,New string[] {"Admin"});//token legal, generate principal object into parameters, key "server. User "
The User information that is used to store the current request, equivalent to HttpContext.Userif(Nextappfunc! =NULL) { awaitnextappfunc.invoke (parameters);//Continue execution of the next middleware}} in the pipeline Privatedictionary<string,string> parsequerystring (stringoriginalstring) { string[] Querystringitems = Originalstring.split (New string[] {"&"}, Stringsplitoptions.removeemptyentries); varQuerystringdic =Newdictionary<string,string>(); foreach(varIteminchQuerystringitems) { string[] QUERYSTRINGKVP = Item. Split (New string[] {"="}, Stringsplitoptions.none); if(Querystringkvp.length = =2) {querystringdic[querystringkvp[0]] = querystringkvp[1]; } } returnQuerystringdic; }
}

The previously defined PersonController plus authorize attribute are then protected.

F5 runs and then accesses the following url:http://localhost:8088/api/persons/123/name?token=88888888 in the browser. You can still get the correct return.

If token=88888888 is removed, the following results are obtained.

This shows that our authenticatemiddle play a role.

Complete code See Https://github.com/lbwxly/OwinSample.git

Reference Documentation:

Http://www.dotnetcurry.com/signalr/915/owin-katana-signalr-web-server

https://ovaismehboob.com/2014/12/01/understanding-owin-by-developing-a-custom-owin-middleware-component/

Host ASP. WebApi in Owin

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.