.net core ConfigureWebDefaults 做了什么?

 

 

ConfigureWebDefaults 源码

  1 File: GenericHostBuilderExtensions.cs
  2 Web Access
  3 Project: src\src\DefaultBuilder\src\Microsoft.AspNetCore.csproj (Microsoft.AspNetCore)
 74 // Licensed to the .NET Foundation under one or more agreements.
 75 // The .NET Foundation licenses this file to you under the MIT license.
 76  
 77 using Microsoft.AspNetCore;
 78 using Microsoft.AspNetCore.Hosting;
 79  
 80 namespace Microsoft.Extensions.Hosting;
 81  
 82 /// <summary>
 83 /// Extension methods for configuring the <see cref="IHostBuilder" />.
 84 /// </summary>
 85 public static class GenericHostBuilderExtensions
 86 {
 87     /// <summary>
 88     /// Configures a <see cref="IHostBuilder" /> with defaults for hosting a web app. This should be called
 89     /// before application specific configuration to avoid it overwriting provided services, configuration sources,
 90     /// environments, content root, etc.
 91     /// </summary>
 92     /// <remarks>
 93     /// The following defaults are applied to the <see cref="IHostBuilder"/>:
 94     /// <list type="bullet">
 95     ///     <item><description>use Kestrel as the web server and configure it using the application's configuration providers</description></item>
 96     ///     <item><description>configure <see cref="IWebHostEnvironment.WebRootFileProvider"/> to include static web assets from projects referenced by the entry assembly during development</description></item>
 97     ///     <item><description>adds the HostFiltering middleware</description></item>
 98     ///     <item><description>adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true,</description></item>
 99     ///     <item><description>enable IIS integration</description></item>
100     ///   </list>
101     /// </remarks>
102     /// <param name="builder">The <see cref="IHostBuilder" /> instance to configure.</param>
103     /// <param name="configure">The configure callback</param>
104     /// <returns>A reference to the <paramref name="builder"/> after the operation has completed.</returns>
105     public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure)
106     {
107         ArgumentNullException.ThrowIfNull(configure);
108  
109         return builder.ConfigureWebHostDefaults(configure, _ => { });
110     }
111  
112     /// <summary>
113     /// Configures a <see cref="IHostBuilder" /> with defaults for hosting a web app. This should be called
114     /// before application specific configuration to avoid it overwriting provided services, configuration sources,
115     /// environments, content root, etc.
116     /// </summary>
117     /// <remarks>
118     /// The following defaults are applied to the <see cref="IHostBuilder"/>:
119     /// <list type="bullet">
120     ///     <item><description>use Kestrel as the web server and configure it using the application's configuration providers</description></item>
121     ///     <item><description>configure <see cref="IWebHostEnvironment.WebRootFileProvider"/> to include static web assets from projects referenced by the entry assembly during development</description></item>
122     ///     <item><description>adds the HostFiltering middleware</description></item>
123     ///     <item><description>adds the ForwardedHeaders middleware if ASPNETCORE_FORWARDEDHEADERS_ENABLED=true,</description></item>
124     ///     <item><description>enable IIS integration</description></item>
125     ///   </list>
126     /// </remarks>
127     /// <param name="builder">The <see cref="IHostBuilder" /> instance to configure.</param>
128     /// <param name="configure">The configure callback</param>
129     /// <param name="configureOptions">The delegate that configures the <see cref="WebHostBuilderOptions"/>.</param>
130     /// <returns>A reference to the <paramref name="builder"/> after the operation has completed.</returns>
131     public static IHostBuilder ConfigureWebHostDefaults(this IHostBuilder builder, Action<IWebHostBuilder> configure, Action<WebHostBuilderOptions> configureOptions)
132     {
133         ArgumentNullException.ThrowIfNull(configure);
134  
135         return builder.ConfigureWebHost(webHostBuilder =>
136         {
137             WebHost.ConfigureWebDefaults(webHostBuilder);
138  
139             configure(webHostBuilder);
140         }, configureOptions);
141     }
142 }
143 Document OutlineProject ExplorerNamespace Explorer

 


 1   internal static void ConfigureWebDefaults(IWebHostBuilder builder)
 2     {
 3         builder.ConfigureAppConfiguration((ctx, cb) =>
 4         {
 5             if (ctx.HostingEnvironment.IsDevelopment())
 6             {
 7                 StaticWebAssetsLoader.UseStaticWebAssets(ctx.HostingEnvironment, ctx.Configuration);
 8             }
 9         });
10  
11         ConfigureWebDefaultsCore(builder, services =>
12         {
13             services.AddRouting();
14         });
15  
16         builder
17             .UseIIS()
18             .UseIISIntegration();
19     }

 


  1 File: WebHostBuilderIISExtensions.cs
  2 Web Access
  3 Project: src\src\Servers\IIS\IIS\src\Microsoft.AspNetCore.Server.IIS.csproj (Microsoft.AspNetCore.Server.IIS)
 66 // Licensed to the .NET Foundation under one or more agreements.
 67 // The .NET Foundation licenses this file to you under the MIT license.
 68  
 69 using Microsoft.AspNetCore.Builder;
 70 using Microsoft.AspNetCore.Hosting.Server;
 71 using Microsoft.AspNetCore.Server.IIS;
 72 using Microsoft.AspNetCore.Server.IIS.Core;
 73 using Microsoft.Extensions.DependencyInjection;
 74  
 75 namespace Microsoft.AspNetCore.Hosting;
 76  
 77 /// <summary>
 78 /// Extension methods for the IIS In-Process.
 79 /// </summary>
 80 public static class WebHostBuilderIISExtensions
 81 {
 82     /// <summary>
 83     /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
 84     /// The app will also be configured to capture startup errors.
 85     /// </summary>
 86     /// <param name="hostBuilder">The <see cref="IWebHostBuilder"/> to configure.</param>
 87     /// <returns>The <see cref="IWebHostBuilder"/>.</returns>
 88     public static IWebHostBuilder UseIIS(this IWebHostBuilder hostBuilder)
 89     {
 90         ArgumentNullException.ThrowIfNull(hostBuilder);
 91  
 92         // Check if in process
 93         if (OperatingSystem.IsWindows() && NativeMethods.IsAspNetCoreModuleLoaded())
 94         {
 95             var iisConfigData = NativeMethods.HttpGetApplicationProperties();
 96             // Trim trailing slash to be consistent with other servers
 97             var contentRoot = iisConfigData.pwzFullApplicationPath.TrimEnd(Path.DirectorySeparatorChar);
 98             hostBuilder.UseContentRoot(contentRoot);
 99             return hostBuilder.ConfigureServices(
100                 services =>
101                 {
102                     services.AddSingleton(new IISNativeApplication(new NativeSafeHandle(iisConfigData.pNativeApplication)));
103                     services.AddSingleton<IServer, IISHttpServer>();
104                     services.AddTransient<IISServerAuthenticationHandlerInternal>();
105                     services.AddSingleton<IStartupFilter, IISServerSetupFilter>();
106                     services.AddAuthenticationCore();
107                     services.AddSingleton<IServerIntegratedAuth>(_ => new ServerIntegratedAuth()
108                     {
109                         IsEnabled = iisConfigData.fWindowsAuthEnabled || iisConfigData.fBasicAuthEnabled,
110                         AuthenticationScheme = IISServerDefaults.AuthenticationScheme
111                     });
112                     services.Configure<IISServerOptions>(
113                         options =>
114                         {
115                             options.ServerAddresses = iisConfigData.pwzBindings.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
116                             options.ForwardWindowsAuthentication = iisConfigData.fWindowsAuthEnabled || iisConfigData.fBasicAuthEnabled;
117                             options.MaxRequestBodySize = iisConfigData.maxRequestBodySize;
118                             options.IisMaxRequestSizeLimit = iisConfigData.maxRequestBodySize;
119                         }
120                     );
121                 });
122         }
123  
124         return hostBuilder;
125     }
126 }
127 Document OutlineProject ExplorerNamespace Explorer

 


  1 File: WebHostBuilderIISExtensions.cs
  2 Web Access
  3 Project: src\src\Servers\IIS\IISIntegration\src\Microsoft.AspNetCore.Server.IISIntegration.csproj (Microsoft.AspNetCore.Server.IISIntegration)
110 107
111 // Licensed to the .NET Foundation under one or more agreements.
112 // The .NET Foundation licenses this file to you under the MIT license.
113  
114 using Microsoft.AspNetCore.Builder;
115 using Microsoft.AspNetCore.Hosting.Server;
116 using Microsoft.AspNetCore.Http;
117 using Microsoft.AspNetCore.HttpOverrides;
118 using Microsoft.AspNetCore.Server.IISIntegration;
119 using Microsoft.Extensions.DependencyInjection;
120  
121 namespace Microsoft.AspNetCore.Hosting;
122  
123 /// <summary>
124 /// Extension methods for the IIS Out-Of-Process.
125 /// </summary>
126 public static class WebHostBuilderIISExtensions
127 {
128     // These are defined as ASPNETCORE_ environment variables by IIS's AspNetCoreModule.
129     private const string ServerPort = "PORT";
130     private const string ServerPath = "APPL_PATH";
131     private const string PairingToken = "TOKEN";
132     private const string IISAuth = "IIS_HTTPAUTH";
133     private const string IISWebSockets = "IIS_WEBSOCKETS_SUPPORTED";
134  
135     /// <summary>
136     /// Configures the port and base path the server should listen on when running behind AspNetCoreModule.
137     /// The app will also be configured to capture startup errors.
138     /// </summary>
139     /// <param name="hostBuilder"></param>
140     /// <returns></returns>
141     public static IWebHostBuilder UseIISIntegration(this IWebHostBuilder hostBuilder)
142     {
143         ArgumentNullException.ThrowIfNull(hostBuilder);
144  
145         // Check if `UseIISIntegration` was called already
146         if (hostBuilder.GetSetting(nameof(UseIISIntegration)) != null)
147         {
148             return hostBuilder;
149         }
150  
151         var port = hostBuilder.GetSetting(ServerPort) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPort}");
152         var path = hostBuilder.GetSetting(ServerPath) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{ServerPath}");
153         var pairingToken = hostBuilder.GetSetting(PairingToken) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{PairingToken}");
154         var iisAuth = hostBuilder.GetSetting(IISAuth) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{IISAuth}");
155         var websocketsSupported = hostBuilder.GetSetting(IISWebSockets) ?? Environment.GetEnvironmentVariable($"ASPNETCORE_{IISWebSockets}");
156  
157         bool isWebSocketsSupported;
158         if (!bool.TryParse(websocketsSupported, out isWebSocketsSupported))
159         {
160             // If the websocket support variable is not set, we will always fallback to assuming websockets are enabled.
161             isWebSocketsSupported = (Environment.OSVersion.Version >= new Version(6, 2));
162         }
163  
164         if (!string.IsNullOrEmpty(port) && !string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(pairingToken))
165         {
166             // Set flag to prevent double service configuration
167             hostBuilder.UseSetting(nameof(UseIISIntegration), true.ToString());
168  
169             var enableAuth = false;
170             if (string.IsNullOrEmpty(iisAuth))
171             {
172                 // back compat with older ANCM versions
173                 enableAuth = true;
174             }
175             else
176             {
177                 // Lightup a new ANCM variable that tells us if auth is enabled.
178                 foreach (var authType in iisAuth.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
179                 {
180                     if (!string.Equals(authType, "anonymous", StringComparison.OrdinalIgnoreCase))
181                     {
182                         enableAuth = true;
183                         break;
184                     }
185                 }
186             }
187  
188             var address = "http://127.0.0.1:" + port;
189             hostBuilder.CaptureStartupErrors(true);
190  
191             hostBuilder.ConfigureServices(services =>
192             {
193                 // Delay register the url so users don't accidentally overwrite it.
194                 hostBuilder.UseSetting(WebHostDefaults.ServerUrlsKey, address);
195                 hostBuilder.PreferHostingUrls(true);
196                 services.AddSingleton<IServerIntegratedAuth>(_ => new ServerIntegratedAuth()
197                 {
198                     IsEnabled = enableAuth,
199                     AuthenticationScheme = IISDefaults.AuthenticationScheme
200                 });
201                 services.AddSingleton<IStartupFilter>(new IISSetupFilter(pairingToken, new PathString(path), isWebSocketsSupported));
202                 services.Configure<ForwardedHeadersOptions>(options =>
203                 {
204                     options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
205                 });
206                 services.Configure<IISOptions>(options =>
207                 {
208                     options.ForwardWindowsAuthentication = enableAuth;
209                 });
210                 services.AddAuthenticationCore();
211             });
212         }
213  
214         return hostBuilder;
215     }
216 }
217 Document OutlineProject ExplorerNamespace Explorer

 

 

posted on 2023-02-24 00:59  是水饺不是水饺  阅读(29)  评论(0编辑  收藏  举报

导航