Asp.net webapi self-managed plug-in service, asp. netwebapi

Source: Internet
Author: User

Asp.net webapi self-managed plug-in service, asp. netwebapi

Webapi has been around for a long time, and many confused people use mvc. After all, experience with mvc can cope with webapi.

Webapi and mvc in asp. the combination of the net5 era tells us that there are still differences between the two, or they will not get two names now, but due to my poor ability to sum up, the differences cannot be listed one by one.

 

In webapi, HelpPage is a prominent and practical thing. Nima will generate xml for the comments in our code, and then display the interface document in webpages, this Nima has laid off a batch of texts. From the perspective of social responsibility, ms's HelpPage is not authentic, but I like it ..

The procedure is also simple:

1. Search for helppage in negut and check that the Id is Microsoft. AspNet. WebApi. HelpPage and Install it;

2. Create an xml file and select the path of the xml file in project properties-generate;

3. Introduce HelpPageConfig. cs in the generated HelpPage. The Code "config. SetDocumentationProvider (new XmlDocumentationProvider (HttpContext. Current. Server. MapPath ("~ /App_Data/ApiDocument. xml ");", modify the xml path, and then uncomment;

4. In the last life, you will find that all the comments you have written are inserted into the xml file. When you access help/index, you will see the following diagram:

(For detailed reference: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages)

    

 

5. Negut identifies the Id: WebApiTestClient. Install it. You will find that one js file, one cs file, and two cshtml files are all started with TestClient, don't forget to rely on it when using it elsewhere.

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")}

Click an interface and then stamp the Test Api to Test the interface for your project. At this moment, you will be more confident in your existence as a code farmer. We are not coder, we do not produce code, we are just code porters.

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

    

 

 

After slight nonsense, the theme is entered. After all, the essence of the article should be hidden behind.

From the title of the article, it can be divided into two parts: webapi can host iis, console, winform, winservice and so on, and plug-in development is no stranger to everyone, so the essence is concise, this is also helpless.

1. Use Self Host Self-managed mode, negut-Id: Microsoft. AspNet. WebApi. SelfHost

1.1 first prepare a contrler 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[]          {              new 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", Price = 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 on the console, listen to the port, configure the route, and start the service at a glance

Class Program {static void Main (string [] args) {Console. writeLine ("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 Use winservice to carry webapi services

First, Install-Package Microsoft. AspNet. WebApi. OwinSelfHost (I can describe Asp. Net Owin in one sentence. Asp. Net5 is a cross-platform service. This is a great task)

After the winserver project is created, you can create a new Owin startup category and configure webapi in it.

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-type services seem to have a high level of pressure. In fact, it's just the title party, and the code is very eye-catching...

Override DefaultAssembliesResolver's GetAssemblies, reflection and load the controller in the dll under the specified file, and add 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 the configuration // 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 ;}}

You can write the dll directly to the dynamic_services folder.

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.