从/通过控制台构建的ASP.NET Web Api [英] ASP.NET Web Api built from/with Console

查看:106
本文介绍了从/通过控制台构建的ASP.NET Web Api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用打开的 ASP.Net Web Api 并输出到控制台

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

之所以这样,是因为在启动Web Api之前,我要初始化很多元素和对象。然后,我通过依赖注入注册这些对象,以在我的 ApiController 中访问它们。

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.

当我启动Web Api时,我需要打开控制台,这样我才能看到事情是如何初始化的以及需要多长时间。

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.

我知道可以将日志从Web Api发送到调试控制台,但这不是我想要的。

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

也许有一种方法可以启动控制台项目并将Web Api框架并入其中?

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

推荐答案

OWIN方式:


  1. 创建控制台应用

  2. 将 Microsoft.AspNet.WebApi.OwinSelfHost包及其依赖项添加到项目中

  3. 使用以下命令添加Startup.cs文件内容:

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


  • 修改项目的Main()

  • 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
            }
        }
    }
    


  • 使用动作方法和测试定义控制器。

  • Define a controller with action method and test.

    这篇关于从/通过控制台构建的ASP.NET Web Api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆