OWIN self-hosted mode WEBAPI project, WEBAPI layer as a separate class library for OWIN invocation

Source: Internet
Author: User
Tags hosting

Why do we need to owin in the past, IIS as the. NET developer is the most common Web Server (not one), stems from the tight coupling of Microsoft products, we have to deploy website, Web application, Web API, etc. on IIS, In fact, 2010 years ago There is nothing wrong, but with the development of the web in recent years, especially the rapid development of mobile Internet, IIS as a Web server has exposed his shortcomings. Mainly in two respects, the ASP. System.Web tightly coupled iis,iis tightly coupled OS, which means that our WEB framework must be deployed on Microsoft's operating system, which is difficult to cross-platform. ... What is Owin? In this article do not repeat, there are many online introduction Owin information and advantages and disadvantages of the blog, here can give a few links to your own reference: 1, HTTP://WWW.CNBLOGS.COM/DUDU/P/WHAT-IS-OWIN.HTML2, http:/ /BLOG.CSDN.NET/HK_5788/ARTICLE/DETAILS/51607211: Below we focus on the process of building Owin self-hosting platform, for I am learning process, for people who want to contact him, is also a kind of help. Many people build OWIN+WEBAPI projects are written in a project, I personally for the isolation of the code, the controller layer is written in another project, so as to facilitate the formation of large-scale framework later. Here are the steps to build: 1. Start with a new console application and a. NETFramework Class Library project, the console references the class Library project. The project structure looks like this:

OWIN. WebApi WEBAPI Layer

OWIN. WEBAPI.SV WEBAPI service layer, will be as a startup item!

2. The console project uses NuGet to reference the required class library: OWIN Microsoft.Owin.Hosting Microsoft.Owin.Host.HttpListener Microsoct.AspNet.WebApi.Owin  You need to manually find a reference to the Web class library such as System.web.web,system.net.http from within the WEBAPI project. OWIN. Webapi.srv Layer Reference situation (I have cross-domain configuration, not required to ignore) in the OWIN.WEBAPI layer, we need the same reference to the Web class library, we can inherit from the WEBAPI Project controller layer from apicontroller    OWIN. WEBAPI layer of reference situation (I have cross-domain configuration, do not need to ignore)  3, because the WEBAPI layer to separate class library project write, so here than the general Owin to some more configuration, In the config directory of the OWIN.WEBAPI layer of my project, I created a new Global.cs class, inside the code is the resolution of the controller, the code is shown as follows:
  1 using System.Web.Http;  2 using System.Web.Http.Dispatcher;  3 using System;  4 using System.Collections.Concurrent;  5 using System.Collections.Generic;  6 using System.Linq;  7 using System.Net;  8 using System.Net.Http; 9 using System.Web.Http.Controllers; Ten to namespace OWIN. Webapi.config {public class WebApiApplication:System.Web.HttpApplication {protected void A Pplication_start ()//ignore the XML return it ' s setting let JSON return only LobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; GlobalConfiguration.Configuration.Formatters.Remove (GlobalConfiguration.Configuration.Formatters.XmlFormatt ER); GlobalConfiguration.Configuration.Services.Replace (typeof (Ihttpcontrollerselector), new Webapicontrollerselector (globalconfiguration.configuration));         23}///<summary>/The Webapicontrollerselector//Author:qixiao//time:201 7-1-31 19:24:32//</summary> public class Webapicontrollerselector:defaulthttpcontrollerselector 3 1 {Private Const string namespaceroutevariablename = "Namespace"; private readonly Httpconfigur ation _configuration; Private ReadOnly lazy<concurrentdictionary<string, type>> _apicontrollercache;         Public Webapicontrollerselector (httpconfiguration configuration) 37:base (configuration) 38 {_configuration = configuration; _apicontrollercache = new Lazy<concurrentdictiona Ry<string, type>> (New func<concurrentdictionary<string, type>> (initializeapicontr Ollercache)); Concurrentdictionary<string, Type> Initializeapicontrollercache () 45 {4       6      Iassembliesresolver assembliesresolver = this._configuration. Services.getassembliesresolver (); var types = this._configuration. Services.gethttpcontrollertyperesolver () 48. Getcontrollertypes (Assembliesresolver). ToDictionary (t = t.fullname, t = t); concurrentdictionary<string return new, type> (types); Ienumerable<string> Getcontrollerfullname (httprequestmessage request, String cont Rollername) (NamespaceName), and the var data = Request. Getroutedata (); ienumerable<string> keys = _apicontrollercache.value.todictionary<keyvaluepair<string, Type> , String, type> (T-t.key, +-t = T.value, stringcomparer.currentcultureignorecase). Keys.tolist (); if (!data. Values.trygetvalue (Namespaceroutevariablename, Out NamespaceName)) (froM k in Keys, where K.endswith (string. Format (". { 0}{1} ", Controllername, Defaulthttpcontrollerselector.controllersuffix), Stringcomparison.curren tcultureignorecase) th select K; String[] namespaces = (string[]) namespacename; The return from N in namespaces the join K in keys on string. Format ("{0}.{ 1}{2} ", N, Controllername, Defaulthttpcontrollerselector.controllersuffix). ToLower () equals K.tolower (), select K;         Httpcontrollerdescriptor Selectcontroller (Httprequestmessage request) 76 {ARGUMENTN type type; + if (request = = NULL) + + + throw new Ullexception ("request"); Bayi} controllername string = this. Getcontrollername (Request); if (string. IsNullOrEmpty (controllErname)) (Request.) (Httpresponseexception) Createerrorresponse (Httpstatuscode.notfound, and the string. Format ("No route providing a controller name is found to match request URI ' {0} '", new object[] {request. RequestUri})); ienumerable<string> fullnames = getcontrollerfullname (request, controllername); if (fullnames.count () = = 0), the httpresponseexception (request. Createerrorresponse (Httpstatuscode.notfound, String. Format ("No route providing a controller name is found to match request URI ' {0} '", new object[] {request. RequestUri}));             94 (This._apicontrollercache.value.trygetvalue (Fullnames.first (), out type) 96             {Httpcontrollerdescriptor return new (_configuration, controllername, type); 98} 99 throw new HttpresponSeexception (Request. Createerrorresponse (httpstatuscode.notfound,100 string. Format ("No route providing a controller name is found to match request URI ' {0} '", new object[] {request. RequestUri})); 101}102}103}

4, create a new AppStart.cs class inside the OWIN.WEBAPI.SRV layer, and write the following code:

 1 using Microsoft.Owin.Hosting; 2 using System; 3 using Owin; 4 using System.Web.Http; 5 using System.Web.Http.Dispatcher; 6 using QX_Frame.App.WebApi.Extends; 7 using System.Web.Http.Cors; 8 9 namespace OWIN. WEBAPI.SRV10 {One class AppStart12 {$ static void Main (string[] args)-{//string b    aseaddress = "http://localhost:3999/";              localhost visit16 string baseaddress = "http://+:3999/"; All Internet environment visit Try18 {webapp.start<startup> (url:ba seaddress) Console.WriteLine ("Baseipaddress is" + baseaddress); Console.WriteLine ("\ Napplication Started! "); }23 catch (Exception ex), {Console.WriteLine (ex). ToString ());}27 (;;) {console.readline ();}32}33}34//the start up Configuration35 class StartUp36 {PNs public void Configuration (Iappbuilder AppBuilder) 38 {39             httpconfiguration config = new httpconfiguration (); Web API Configuration and Services42 Cross-domain Configuration//need reference from Nuget43 config. Enablecors (New Enablecorsattribute ("*", "*", "*")),//enabing attribute routing45 config. Maphttpattributeroutes ();//Web API convention-based routing.47 config.                 Routes.maphttproute ("Defaultapi", Routetemplate: "Api/{controller}/{id}", 50 defaults:new {id = routeparameter.optional},51 namespaces:new string[] {"OWIN. WebApi "}52); Services.replace (typeof (Ihttpcontrollerselector), new OWIN.  WebApi.config.WebApiControllerSelector (config));//if config The global filter input there need not write The ATTRIBUTES56            Config. Filters.add (New App.Web.Filters.ExceptionAttribute_DG ());//new classregisters (); Register IOC menbers59 Appbuilder.usewebapi (config); 61}62}63}

Inside the address is configured, of course, according to the needs of self-configuration, display information is also carried out the appropriate display, it should be noted that I have a cross-domain configuration here, no configuration or no need to comment out and ignore!

The note here is the 53rd line, here is referring to the OWIN.WEBAPI layer of the Global.cs inside the class, please compare the above two code to find.

This line is the key, with this line, the program can scan to the WEBAPI layer controller. Well, we'll do the controller's writing. 5, in the OWIN.WEBAPI layer to write the controller class, here arbitrarily, I only listed here my example.
 1 using QX_Frame.App.WebApi; 2 using QX_FRAME.HELPER_DG; 3 using System.Web.Http; 4 5 namespace OWIN. WEBAPI 6 {7/* 8 * Author:qixiao 9 * time:2017-2-27 10:32:5710 **/11 public class Test1controller: ApiController12 {//access http://localhost:3999/api/Test1 get method14 public ihttpactionresult Ge             TTest () {//throw new EXCEPTION_DG ("Login ID, pwd", "argumets can not is null", 11111, 2222); 17 Return Json (New {issuccess = true, MSG = "This is Get Method"})}19//access Http://localh Ost:3999/api/test1 post METHOD20 public ihttpactionresult posttest (Dynamic Querydata) (R) Eturn Json (New {issuccess = true, MSG = "This is Post method", Data=querydata});}24//access Http://lo Calhost:3999/api/test1 put METHOD25 public ihttpactionresult puttest () + {return Json (new {issuccess = true, MSG = "This is put methOd "});}29//access http://localhost:3999/api/Test1 Delete method30 public ihttpactionresult D     Eletetest () {return Json (new {issuccess = true, MSG = "This is Delete method"}); 33}34 }35}

Here I am using the Restfull-style WEBAPI controller interface.

Then we can run the test:

Service started successfully!

Test pass, we can explore the follow-up development steps heartily!

OWIN self-hosted mode WEBAPI project, WEBAPI layer as a separate class library for OWIN invocation

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.