ASP. NET Webapi self-hosted plug-in service

Source: Internet
Author: User
Tags what interface

Webapi has been a long time, the confused people it all as MVC, after all, has been MVC use level of experience can deal with WEBAPI.

Webapi and MVC in the Asp.net5 era, this tells us, in fact, they still have a difference, or now will not take two names, but because I summed up the ability is poor, a variety of different can not be listed.

In the Webapi Helppage is a prominent and practical things, it will put our code in the comments generated XML, and then a Web page to show the interface document, which Nima invisible on the laid-off a batch of copy, in terms of social responsibility, This helppage of MS is quite unusual, but I say I like this kind of thing.

The steps are also simple:

1, Negut search helppage, look for ID is Microsoft.AspNet.WebApi.HelpPage install it;

2. Create a new XML file in the project properties-Generate an XML document file path pointing to it tick;

3, introduce the generated helppage in HelpPageConfig.cs, this Code "config. Setdocumentationprovider (New Xmldocumentationprovider (HttpContext.Current.Server.MapPath ("~/app_data/ Apidocument.xml "));", modify the XML path and then extract the annotation;

4, the final generation will find that you write and no egg annotation is a lump of a lump into the XML file, when access to Help/index will see the map as follows:

(attached to a detailed reference: Http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages)

    

5, Negut look id:webapitestclient,install it, you will find a JS, a CS, two cshtml files, are testclient at the beginning of the use of other times do not forget to rely on it.

Add two lines of code to the api.cshtml file

@Html. Displayformodel ("Testclientdialogs") @section scripts{    <link href= "~/areas/helppage/testclient.css" rel= "stylesheet"/>    @Html. Displayformodel ("Testclientreferences")}

After you have entered an interface, poke the test Api and your project will be tested for interfaces. Now you will be more determined to be the existence of yards, we are not coder, we do not produce code, we are just code porters.

(attached to a detailed reference: https://blogs.msdn.microsoft.com/yaohuang1/2012/12/02/adding-a-simple-test-client-to-asp-net-web-api-help-page/)

    

After the micro-width, words into the theme, after all, the essence of the article to hide behind.

From the article title, can be divided into two parts, Webapi can be hosted IIS, console, WinForm, WinService, plug-in development we are not unfamiliar, so the essence of the part is also concise, this is very helpless thing ah.

1. Using self host, negut-id:microsoft.aspnet.webapi.selfhost

1.1 First prepare a contrller and model, the code is very simple

public class Product {public int Id {get; set;}        public string Name {get; set;}        public string Category {get; set;}    Public decimal price {get; set;} }public class Productscontroller:apicontroller {product[] products = new product[] {NE W 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 ", Pri        CE = 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)); }    }

1.2 Host in console, monitor port, configure route, start service, at a glance

Class program    {        static void Main (string[] args)        {            Console.WriteLine ("Please enter the listening port");            String port = Console.ReadLine ();            var config = new Httpselfhostconfiguration (string. Format ("http://localhost:{0}", Port?? "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 ESC to quit.");                while (               ! Console.readkey (). Key.equals (Consolekey.escape))                {}}}}    

1.3 using WinService to carry WEBAPI services

First: install-package Microsoft.AspNet.WebApi.OwinSelfHost (referring to the ASP. Owin words can be described, Asp.net5 Cross-platform, this force must not be AH)

After you create a new Winserver project, you can create a new Owin startup category in which to build the WEBAPI configuration

public class Startup    {public        void Configuration (Iappbuilder appBuilder)        {            //Configure Web API for Self-host.             httpconfiguration config = new httpconfiguration ();            Config. Routes.maphttproute (                name: "Defaultapi",                routetemplate: "Api/{controller}/{id}",                defaults:new {id = Routeparameter.optional}            );            Config. Services.replace (typeof (Iassembliesresolver), New Pluginsresolver ());            Appbuilder.usewebapi (config);        }    }

Start in service, over.

Private IDisposable _apiserver = null;        protected override void OnStart (string[] args)        {            //services URI             String Serveruri = string. Format ("http://localhost:{0}/", system.configuration.configurationmanager.appsettings["Port"]);            Start OWIN host              _apiserver = webapp.start<startup> (Url:serveruri);            Base. OnStart (args);        }        protected override void OnStop ()        {            if (_apiserver! = null)            {                _apiserver. Dispose ();            }            Base. OnStop ();        }

2, plug-in services, seemingly forcing lattice is very high, in fact, just the title of the party, the finishing touch of the code to the ...

Rewrite defaultassembliesresolver getassemblies, reflection loads the controller in the DLL under the specified file, adding its implementation in WEBAPICONIFG

public class Pluginsresolver:defaultassembliesresolver    {public        override icollection<assembly> Getassemblies ()        {            ///dynamically load the controller in the DLL, similar to the plug-in service, add config            /config in WEBAPICONIFG. Services.replace (typeof (Iassembliesresolver), New Pluginsresolver ());            list<assembly> assemblies = new List<assembly> (base. Getassemblies ());            String directorypath = Path.Combine (System.AppDomain.CurrentDomain.BaseDirectory, "dynamic_services");            string[] files = directory.getfiles (directorypath);            foreach (var fileName in files)            {                assemblies. ADD (Assembly.LoadFrom (Path.Combine (DirectoryPath, FileName));            }            return assemblies;        }    }

What interface service is required to write the DLL directly is still in the Dynamic_services folder.

ASP. NET Webapi self-hosted plug-in service

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.