C# .NET5 Startup介绍

2021/11/27 9:10:21

本文主要是介绍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# .NET5 Startup介绍的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程