编程语言
首页 > 编程语言> > C# .NET5 Startup介绍

C# .NET5 Startup介绍

作者:互联网

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using System;
using System.IO;
using System.Reflection;

namespace MEAS
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        //解决有没有的问题--服务,配置服务
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "MEAS", Version = "v1" });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.XML";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                //... and tell Swagger to use those XML comments.
                c.IncludeXmlComments(xmlPath);
            });
            services.AddMvc().AddWebApiConventions();//解决返回值是HttpResponseMessage 自己的 json 序列化数据:

            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest).AddJsonOptions(option =>
            //{
            //    //原样输出,默认会把首字母小写
            //    option.JsonSerializerOptions.PropertyNamingPolicy = null;
            //});

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        //解决需不需要的问题--请求处理--中间件,,有顺序要求
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //env.IsProduction
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
               
            }
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MEAS v1"));//发布之后的版本

            //app.UseHttpsRedirection();   解决发布后warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
            //Failed to determine the https port for redirect这个问题.
            //分配路由
            app.UseRouting();
            //认证
            app.UseAuthentication();
            //授权
            app.UseAuthorization();
            //端点
            app.UseEndpoints(endpoints =>
            {
                //控制器路由
                endpoints.MapControllers();
            });
        }
    }
}

  

标签:C#,app,Startup,public,method,services,using,NET5,Microsoft
来源: https://www.cnblogs.com/YYkun/p/15610586.html