简体   繁体   中英

ASP.NET Web Api built from/with Console

I want to be able to use an ASP.Net Web Api that opens and outputs to the Console .

The reason why is because I am initializing a lot of elements and objects before launching the Web Api. Then I register those objects with dependency injection to access them within my ApiController .

When I launch the Web Api, I need the Console to open so I can see how things are being initialized and how long does it takes.

I know it is possible to send logs from the Web Api to the debug console but this isn't what I want.

Maybe there is a way to start a console project and incorporate the Web Api framework into it ?

OWIN way:

  1. Create a Console App
  2. Add "Microsoft.AspNet.WebApi.OwinSelfHost" package and its dependencies to the project
  3. Add Startup.cs file with the following content:

     using Owin; using System.Web.Http; namespace YourConsoleAppProjectNamespace { public class Startup { public void Configuration(IAppBuilder appBuilder) { HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); appBuilder.UseWebApi(config); } } }
  4. Modify your project's Main()

     using Microsoft.Owin.Hosting; using System; namespace YourConsoleAppProjectNamespace { class Program { static void Main(string[] args) { WebApp.Start<Startup>("http://localhost:3333/"); Console.ReadLine(); // block main thread } } }
  5. Define a controller with action method and test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM