有时候我们不需要将WebAPI发布到iis上运行,需要将webapi内嵌到cs程序内部,随程序一起启动,其实比较简单,需要一个类,如下
public class Startup { public static HttpSelfHostServer m_serverhost = null; public static void IniWebApi() { HttpSelfHostConfiguration _config = new HttpSelfHostConfiguration("http://localhost:4545"); _config.MaxReceivedMessageSize=int.MaxValue; _config.MaxBufferSize = int.MaxValue; _config.Routes.MapHttpRoute( name: "DefaultApinew", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); //start m_serverhost = new HttpSelfHostServer(_config); m_serverhost.OpenAsync().Wait(); } }
然后启动的时候 调用IniWebApi函数就可以了