使用控制台作为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测试

 

测试带参数

 

posted @ 2023-03-07 16:55  .NET开发菜鸟  阅读(1893)  评论(0编辑  收藏  举报