ASP.NET5已經把web服務從應用程序當中解耦出來了,它支持IIS和IIS Express, 用Kestrel和WebListener自宿主,另外,開發都或者第三方軟件提供商均可以自定義開發ASP.NET5應用程序的宿主服務。web
在ASP.NET5當中推薦的作法是利用IIS作爲反向代碼服務,HttpPlatformHandler模塊管理和把請求代理髮送到HTTP服務,ASP.NET5提供兩個服務:編程
1. Microsoft.AspNet.Server.WebListener ( 只能用於WIndows )json
2. Microsoft.AspNet.Server.Kestrel ( 跨平臺的 )app
ASP.NET5 不直接監聽請求,而是依賴於HTTP服務把特性接口封裝到HttpContext當中。async
服務的依賴被定義在project.json當中。例如:ui
"commands": {url
"run": "run server.urls=http://localhost:5003",代理
"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://localhost:5000",orm
"weblistener":"Microsoft.AspNet.Hosting --server WebListener --server.urls http://localhost:5004"server
},
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);
});
}