ASP.NET 5服务

时间:2021-12-05 04:48:56

ASP.NET5已经把web服务从应用程序当中解耦出来了,它支持IIS和IIS Express, 用Kestrel和WebListener自宿主,另外,开发都或者第三方软件提供商都可以自定义开发ASP.NET5应用程序的宿主服务。

在ASP.NET5当中推荐的做法是利用IIS做为反向代码服务,HttpPlatformHandler模块管理和把请求代理发送到HTTP服务,ASP.NET5提供两个服务:

1. Microsoft.AspNet.Server.WebListener ( 只能用于WIndows )

2. Microsoft.AspNet.Server.Kestrel ( 跨平台的 )

ASP.NET5 不直接监听请求,而是依赖于HTTP服务把特性接口封装到HttpContext当中。

服务的依赖被定义在project.json当中。例如:

"commands": {

  "run": "run server.urls=http://localhost:5003",

  "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000",

  "weblistener":"Microsoft.AspNet.Hosting --server WebListener --server.urls http://localhost:5004"

},

run命令从void main方法开始执行应用程序:

public Task<int> Main(string[] args)

{

  var builder = new ConfigurationBuilder();

  builder.AddCommandLine(args);

  var config = builder.Build();

  

  using(new WebHostBuilder(config).

UseServer("Microsoft.AspNet.Server.Kestrel").Build().Start())

  {

    Console.WriteLine("Started the server..");

    Console.WrtieLine("Preess any key to stop the server");

    Console.ReadLine();

  }

  return Task.FromResult(0);

}

服务支持的功能:

Feature           WebListener    Kestrel

IHttpRequestFeature  Yes        Yes

IHttpResponseFeature  Yes        Yes

IHttpAuthenticationFeature  Yes      No

IHttpUpgradeFeature    Yes(with limits)      Yes

IHttpBufferingFeature    Yes        No

IHttpConnectionFeature    Yes       Yes

IHttpRequestLifetimeFeature  Yes      No

IHttpSendFileFeature      Yes      No

IHttpWebSocketFeature    No      No

IRequestIdentifierFeature    Yes      No

ITlsConnectionFeature      Yes      Yes

ITlsTokenBindingFeature      Yes      No

编程的方式配置:

public void Configure(IApplicationBuilder app, IApplicationLifetime lifetime, ILoggerFactory loggerFactory)

{

  var webListenerInfo = app.ServerFeatures.Get<WebListener>();

  if(webListenerInfo != null)

  {

    webListenerInfo.AuthenticationManager.AuthenticationSchemes =

      AuthenticationSchemes.AllowAnonymous;

  }

  var serverAddress = app.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses.FirstOrDefault();

  app.Run(async (context) =>

  {

    var message = String.Format("Hello World from{0}", serverAddress);

    await context.Response.WriteAsync(message);

  });

}