简体   繁体   English

如何将 ASP.NET Core 3.1 中 Startup.cs 中的代码移动到 ASP.NET Core 6?

[英]How to move code in Startup.cs in ASP.NET Core 3.1 to ASP.NET Core 6?

I re-use source code from this project https://www.c-sharpcorner.com/article/custome-jwt-token-and-asp-net-core-web-api/ , download project at https://www.c-sharpcorner.com/article/custome-jwt-token-and-asp-net-core-web-api//download/JWTTokenPOC.zip我重用了这个项目https://www.c-sharpcorner.com/article/custome-jwt-token-and-asp-net-core-web-api/的源代码,在https://www下载项目.c-sharpcorner.com/article/custome-jwt-token-and-asp-net-core-web-api//download/JWTTokenPOC.zip

This is ASP.NET Core API version 3.x, it has这是 ASP.NET 内核 API 版本 3.x,它有

在此处输入图像描述

File Startup.cs文件Startup.cs

using JWTTokenPOC.Helper;
using JWTTokenPOC.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace JWTTokenPOC
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }


        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
           services.AddCors();
           services.AddControllers();
            // configure to get Appsetting section from appsetting.json
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
            services.AddScoped<IUserService, UserService>();
            services.AddScoped<IAuthenticationService, AuthenticationService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           
            app.UseRouting();
            // set global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            // Custom jwt auth middleware to authenticate the token
            app.UseMiddleware<JwtMiddleware>();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Now, I code ASP.NET Core WebAPI 6.x project.现在,我编写 ASP.NET Core WebAPI 6.x 项目。

在此处输入图像描述

I dont' have Startup.cs in project, I just have file Program.cs我在项目中没有Startup.cs ,我只有文件Program.cs

using acc7.Data;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Identity.Web;
using Microsoft.Identity.Web.Resource;

namespace acc7
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

            var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
            // builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql(connectionString));
            builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseNpgsql("Server=127.0.0.1;Port=5432;Database=acc200;User Id=postgres;Password=postgres;"));

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseAuthentication();
            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}

Please guide me migration code from ASP.NET Core WebAPI version 3.1 project --> ASP.NET Core WebAPI version 6.x project.请指导我从 ASP.NET Core WebAPI 3.1 版项目迁移代码 --> ASP.NET Core WebAPI 6.x 版项目。 I need feature JWT authentication.我需要功能 JWT 身份验证。

(I don't program C# and ASP.NET Core frequently, every day code Java server-side) (我不经常编程C#和ASP.NET内核,每天代码Java服务器端)

You can re-use your Startup class like this:您可以像这样重复使用您的Startup class:

var builder = WebApplication.CreateBuilder(args);

// Manually create an instance of the Startup class
var startup = new Startup(builder.Configuration);

// Manually call ConfigureServices()
startup.ConfigureServices(builder.Services);

var app = builder.Build();

// Fetch all the dependencies from the DI container 
// var hostLifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
// As pointed out by DavidFowler, IHostApplicationLifetime is exposed directly on ApplicationBuilder

// Call Configure(), passing in the dependencies
startup.Configure(app, app.Lifetime);

app.Run();

Source:资源:

https://andrewlock.net/exploring-dotnet-6-part-12-upgrading-a-dotnet-5-startup-based-app-to-dotnet-6/#option-2-re-use-your-startup-class https://andrewlock.net/exploring-dotnet-6-part-12-upgrading-a-dotnet-5-startup-based-app-to-dotnet-6/#option-2-re-use-your-startup -班级

In configure services, you are adding your dependencies to register.在配置服务中,您正在添加要注册的依赖项。 So .NET 6 equivalent is to use builder.Services所以 .NET 6 等效是使用builder.Services

For example例如

builder.Services.AddCors();
builder.Services.AddControllers();
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IAuthenticationService, AuthenticationService>();

To configure the request pipeline in .NET 6在 .NET 6 中配置请求管道

var app = builder.Build();

use the app here to build your request pipeline, For example使用此处的应用程序来构建您的请求管道,例如

        app.UseRouting();
        // set global cors policy
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

        // Custom jwt auth middleware to authenticate the token
        app.UseMiddleware<JwtMiddleware>();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM