使用控制檯作爲ASP.NET webapi的宿主

一、前言

一般情況下,我們在使用ASP.NET WebApi的時候習慣創建一個Web應用程序,最終將程序部署到IIS進行運行。但有時候,我們需要在控制檯或者Windows服務中運行webapi程序,這時就不適合使用IIS。這時就可以使用自託管模式。asp.net web api的自託管模式HttpSelfHostServer可以以控制檯程序或windows服務程序爲宿主,不單單依賴於IIS web服務器

注意:這裏使用的是.Net Framework做控制檯或者Windows服務

二、示例代碼

1、創建控制檯程序,項目結構如下

 

2、安裝Microsoft.AspNet.WebApi.SelfHost

通過Nuget安裝Microsoft.AspNet.WebApi.SelfHost,注意選擇對應的.Net Framework版本

 

安裝完以後會包括如下的DLL

  • System.Web.Http.dll
    • The core runtime assembly for ASP.NET Web API
  • System.Net.Http.dll
    • Provides a programming interface for modern HTTP applications. This includes HttpClient for sending requests over HTTP, as well as HttpRequestMessage and HttpResponseMessage for processing HTTP messages
  • System.Net.Http.WebRequest.dll
    • Provides additional classes for programming HTTP applications
  • System.Web.Http.SelfHost.dll
    • Contains everything you need to host ASP.NET Web API within your own process (outside of IIS)
  • System.Net.Http.Formatting.dll
    • Adds support for formatting and content negotiation to System.Net.Http. It includes support for JSON, XML, and form URL encoded data

3、創建Routes路由配置類

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Routing;
using System.Web.Http.SelfHost;

namespace WebApiSelfHostDemo
{
    public class Routes
    {
        public static void ConfigureRoutes(HttpSelfHostConfiguration config)
        {
            config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
            config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
            config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
            config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
        }
    }
}

 

4、創建RestApiServer類

using System;
using System.Web.Http.SelfHost;

namespace WebApiSelfHostDemo
{
    public class RestApiServer
    {
        public const int PORT = 8091;

        private static HttpSelfHostServer _server;
        /// <summary>
        /// start server to listen http request
        /// </summary>
        /// <param name="params"></param>
        public static void StartUp(string[] @params)
        {
            string host = string.Empty;
#if DEBUG
            host = "localhost";
#else
            host = SelfHostHelper.GetHandlerIP();
#endif
            try
            {
                if (_server != null)
                {
                    _server.CloseAsync().Wait();
                    _server.Dispose();
                    _server = null;
                }

                string baseAddress = $"http://{host}:{PORT}";
                var config = new HttpSelfHostConfiguration(baseAddress);
                Console.WriteLine();
                Routes.ConfigureRoutes(config);
                Console.WriteLine("Instantiating The Server...");
                _server = new HttpSelfHostServer(config);
                _server.OpenAsync().Wait();
                Console.WriteLine("Server is Running Now and listen : " + baseAddress);
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public static void ShutDown()
        {
            if (_server != null)
            {
                _server.CloseAsync();
                _server.Dispose();
            }
        }
    }
}

 

5、在Main方法中調用

using System;

namespace WebApiSelfHostDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                RestApiServer.StartUp(new string[] { });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }
    }
}

 

 

運行結果

 

6、添加控制器

using System.Web.Http;

namespace WebApiSelfHostDemo
{
    public class TestSelfHostController  : ApiController
    {
        public string Get() 
        { 
            return "Hi!, Self-Hosted Web Api Application Get"; 
        }


        public string Get(int id) 
        { 
            return $"Hi!, Self-Hosted Web Api Application Get With Id:{id} "; 
        }
    }
}

 

使用Postman測試

 

測試帶參數

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章