.net6 WebApplication源码

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// The web application used to configure the HTTP pipeline, and routes.
    /// </summary>
    public sealed class WebApplication : IHost, IApplicationBuilder, IEndpointRouteBuilder, IAsyncDisposable
    {
        internal const string GlobalEndpointRouteBuilderKey = "__GlobalEndpointRouteBuilder";

        private readonly IHost _host;
        private readonly List<EndpointDataSource> _dataSources = new();

        internal WebApplication(IHost host)
        {
            _host = host;
            ApplicationBuilder = new ApplicationBuilder(host.Services);
            Logger = host.Services.GetRequiredService<ILoggerFactory>().CreateLogger(Environment.ApplicationName);

            Properties[GlobalEndpointRouteBuilderKey] = this;
        }

        /// <summary>
        /// The application's configured services.
        /// </summary>
        public IServiceProvider Services => _host.Services;

        /// <summary>
        /// The application's configured <see cref="IConfiguration"/>.
        /// </summary>
        public IConfiguration Configuration => _host.Services.GetRequiredService<IConfiguration>();

        /// <summary>
        /// The application's configured <see cref="IWebHostEnvironment"/>.
        /// </summary>
        public IWebHostEnvironment Environment => _host.Services.GetRequiredService<IWebHostEnvironment>();

        /// <summary>
        /// Allows consumers to be notified of application lifetime events.
        /// </summary>
        public IHostApplicationLifetime Lifetime => _host.Services.GetRequiredService<IHostApplicationLifetime>();

        /// <summary>
        /// The default logger for the application.
        /// </summary>
        public ILogger Logger { get; }

        /// <summary>
        /// The list of URLs that the HTTP server is bound to.
        /// </summary>
        public ICollection<string> Urls => ServerFeatures.Get<IServerAddressesFeature>()?.Addresses ??
            throw new InvalidOperationException($"{nameof(IServerAddressesFeature)} could not be found.");

        IServiceProvider IApplicationBuilder.ApplicationServices
        {
            get => ApplicationBuilder.ApplicationServices;
            set => ApplicationBuilder.ApplicationServices = value;
        }

        internal IFeatureCollection ServerFeatures => _host.Services.GetRequiredService<IServer>().Features;
        IFeatureCollection IApplicationBuilder.ServerFeatures => ServerFeatures;

        internal IDictionary<string, object?> Properties => ApplicationBuilder.Properties;
        IDictionary<string, object?> IApplicationBuilder.Properties => Properties;

        internal ICollection<EndpointDataSource> DataSources => _dataSources;
        ICollection<EndpointDataSource> IEndpointRouteBuilder.DataSources => DataSources;

        internal ApplicationBuilder ApplicationBuilder { get; }

        IServiceProvider IEndpointRouteBuilder.ServiceProvider => Services;

        /// <summary>
        /// Initializes a new instance of the <see cref="WebApplication"/> class with preconfigured defaults.
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>The <see cref="WebApplication"/>.</returns>
        public static WebApplication Create(string[]? args = null) =>
            new WebApplicationBuilder(new() { Args = args }).Build();

        /// <summary>
        /// Initializes a new instance of the <see cref="WebApplicationBuilder"/> class with preconfigured defaults.
        /// </summary>
        /// <returns>The <see cref="WebApplicationBuilder"/>.</returns>
        public static WebApplicationBuilder CreateBuilder() =>
            new(new());

        /// <summary>
        /// Initializes a new instance of the <see cref="WebApplicationBuilder"/> class with preconfigured defaults.
        /// </summary>
        /// <param name="args">Command line arguments</param>
        /// <returns>The <see cref="WebApplicationBuilder"/>.</returns>
        public static WebApplicationBuilder CreateBuilder(string[] args) =>
            new(new() { Args = args });

        /// <summary>
        /// Initializes a new instance of the <see cref="WebApplicationBuilder"/> class with preconfigured defaults.
        /// </summary>
        /// <param name="options">The <see cref="WebApplicationOptions"/> to configure the <see cref="WebApplicationBuilder"/>.</param>
        /// <returns>The <see cref="WebApplicationBuilder"/>.</returns>
        public static WebApplicationBuilder CreateBuilder(WebApplicationOptions options) =>
            new(options);

        /// <summary>
        /// Start the application.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns>
        /// A <see cref="Task"/> that represents the startup of the <see cref="WebApplication"/>.
        /// Successful completion indicates the HTTP server is ready to accept new requests.
        /// </returns>
        public Task StartAsync(CancellationToken cancellationToken = default) =>
            _host.StartAsync(cancellationToken);

        /// <summary>
        /// Shuts down the application.
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns>
        /// A <see cref="Task"/> that represents the shutdown of the <see cref="WebApplication"/>.
        /// Successful completion indicates that all the HTTP server has stopped.
        /// </returns>
        public Task StopAsync(CancellationToken cancellationToken = default) =>
            _host.StopAsync(cancellationToken);

        /// <summary>
        /// Runs an application and returns a Task that only completes when the token is triggered or shutdown is triggered.
        /// </summary>
        /// <param name="url">The URL to listen to if the server hasn't been configured directly.</param>
        /// <returns>
        /// A <see cref="Task"/> that represents the entire runtime of the <see cref="WebApplication"/> from startup to shutdown.
        /// </returns>
        public Task RunAsync(string? url = null)
        {
            Listen(url);
            return HostingAbstractionsHostExtensions.RunAsync(this);
        }

        /// <summary>
        /// Runs an application and block the calling thread until host shutdown.
        /// </summary>
        /// <param name="url">The URL to listen to if the server hasn't been configured directly.</param>
        public void Run(string? url = null)
        {
            Listen(url);
            HostingAbstractionsHostExtensions.Run(this);
        }

        /// <summary>
        /// Disposes the application.
        /// </summary>
        void IDisposable.Dispose() => _host.Dispose();

        /// <summary>
        /// Disposes the application.
        /// </summary>
        public ValueTask DisposeAsync() => ((IAsyncDisposable)_host).DisposeAsync();

        internal RequestDelegate BuildRequestDelegate() => ApplicationBuilder.Build();
        RequestDelegate IApplicationBuilder.Build() => BuildRequestDelegate();

        // REVIEW: Should this be wrapping another type?
        IApplicationBuilder IApplicationBuilder.New()
        {
            var newBuilder = ApplicationBuilder.New();
            // Remove the route builder so branched pipelines have their own routing world
            newBuilder.Properties.Remove(GlobalEndpointRouteBuilderKey);
            return newBuilder;
        }

        IApplicationBuilder IApplicationBuilder.Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            ApplicationBuilder.Use(middleware);
            return this;
        }

        IApplicationBuilder IEndpointRouteBuilder.CreateApplicationBuilder() => ((IApplicationBuilder)this).New();

        private void Listen(string? url)
        {
            if (url is null)
            {
                return;
            }

            var addresses = ServerFeatures.Get<IServerAddressesFeature>()?.Addresses;
            if (addresses is null)
            {
                throw new InvalidOperationException($"Changing the URL is not supported because no valid {nameof(IServerAddressesFeature)} was found.");
            }
            if (addresses.IsReadOnly)
            {
                throw new InvalidOperationException($"Changing the URL is not supported because {nameof(IServerAddressesFeature.Addresses)} {nameof(ICollection<string>.IsReadOnly)}.");
            }

            addresses.Clear();
            addresses.Add(url);
        }
    }
}

ASP.NET源码包合集6: [博客空间]FcDigg 0.1 Beta_fcdigg.rar [博客空间]FDW.S BLOG源码_myblogs.rar [博客空间]Finesl v1.7.4.50 SP1_finesl.rar [博客空间]FJBLOG博客系统(.Net开源博客系统)_fjblog.rar [博客空间]Hubro Blogv1.0_hubroblog10.rar [博客空间]I-Favourite 3.0 WAP版_wap2.rar [博客空间]IdioBlog(NClay)源码_idioblog.rar [博客空间]IronRuby博客中文版 Alpha_ironruby-pre-alpha1.rar [博客空间]iShuo多用户博客 v1.5_ishuo1.5.rar [博客空间]LalaBlog 2006 v9_lalablog.rar [博客空间]LevenBlog 2.0.8 源码版_levenblogsor.rar [博客空间]LevenBlog 2.0.8_levenblog.rar [博客空间]LiteWiki 0.2.1_litewiki.rar [博客空间]LiveBlog v1.0 测试版_liveblog.rar [博客空间]mBlog个人博客系统 v1.0 Beta2_mblog.rar [博客空间]myblog v1.2 Access版_myblog12a.rar [博客空间]myblog v1.2 SQL版_myblog12s.rar [博客空间]MySite个人展示程序_mysite_blog.rar [博客空间]NClay框架的博客源码_idio_blog.rar [博客空间]Oblog 4.0(ASP.NET非官方版)_oblog4aspx.rar [博客空间]PersonalBlog个人博客源码_personalblog.rar [博客空间]Presstopia Blog v1.0_ptblog.rar [博客空间]Q-Space 晴网个人空间系统 v2.0 Build 20080820 源代码_qspace2.0_src.rar [博客空间]Q-Space 晴网个人空间系统 v2.0 Build 20080820_qspace2.0.rar [博客空间]Roclog 3.2.15 正式版_roclogpub.rar [博客空间]Roclog 4.1.1 正式版_roclog4.rar [博客空间]ScrewTurn Wiki 2.0.37_screwturnwiki.rar [博客空间]Shang Blog v1.1.0 源码版_shangblog_src.rar [博客空间]Shang-Blog v1.0 SP1 ACC版_shang-blogacc.rar [博客空间]Shang-Blog v1.0 SP1 SQl版_shang-blog.rar [博客空间]shenzheBLOG_sblog.rar [博客空间]Solog v1.0(含C#源码)_solog.rar [博客空间]STStudio简单Blog源码_stblog.rar [博客空间]Subtext v1.9.5英文版_subtext-1.9.5.rar [博客空间]SZBlogsAT 深博问测系统存储过程版 v1.0 Build 0415_szblogsat.rar [博客空间]TriptychBlog v.9.0.6 Source_triptychblog_v.9.0.6[src].rar [博客空间]TriptychBlog博客系统 v.9.0.6 汉化版_triptychblog_access.rar [博客空间]wiki.net(网络维基)源码 v1.1_refylwiki.rar [博客空间]WLQ博客系统源码_wlqblog.rar [博客空间]WSBLog v1.6 Beta 2 Build 70325_wsblog.rar
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值