简体   繁体   中英

How to Convert Startup Code from asp.net core 2.1 to Startup Code asp.net Core 3.1

I want to upgrate my project from asp.net core 2.1 to asp.net core 3.1, I have changed the SDK to 3.1 like the below code, but I did not know what to change in my startup code as per need of startup code 3.1

<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

Now I want to update my startup Code from asp.net core 2.1 to asp.net core 3.1 Please modify the below startup code as per the need of asp.net core 3.1

Here is my Startup Code Version asp.net Core 2.1

    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)
    {
        var connection = Configuration.GetConnectionString("DBconnection");
        services.AddDbContext<HoshmandDBContext>(option => option.UseSqlServer(connection));
        services.AddAuthentication(option =>
        {
            option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(options =>
        {
            options.LoginPath = "/Logins/UserLogin/";
            options.AccessDeniedPath = "/AccessDenied";
            options.Cookie.Expiration = new TimeSpan(10,00,00);
        });

        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromHours(2);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;

        });
        
        services.ConfigureApplicationCookie(option =>
        {
            option.ExpireTimeSpan = TimeSpan.FromMinutes(540);
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("HasAccess", policy => policy.AddRequirements(new HasAccessRequirment()));
        });
        services.AddTransient<IAuthorizationHandler, HasAccessHandler>();
        services.AddTransient<IMvcControllerDiscovery, MvcControllerDiscovery>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseCookiePolicy();
        app.UseSession();
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
               template: "{controller=UserProfiles}/{action=Index}/{id?}");
        });
    }
}

Package Manger Reference Code asp.net core 2.1 need to update to asp.net core 3.1

    <ItemGroup>
    <PackageReference Include="BCrypt-Core" Version="2.0.0" />
    <PackageReference Include="ClosedXML" Version="0.97.0" />
    <PackageReference Include="Magick.NET-Q16-AnyCPU" Version="7.8.0" />

    <PackageReference Include="Microsoft.AspNetCore" Version="2.1.7" />
    <PackageReference Include="microsoft.aspnetcore.app" Version="2.1.4" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.1.14" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.14" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.14">
        <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
        <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Logging.Console" Version="2.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="2.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="2.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.10" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="5.0.0" />
    <PackageReference Include="System.Linq.Dynamic.Core" Version="1.2.7" />
</ItemGroup>

<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.3" />
</ItemGroup>

Here is my UserProfile Controller Code, by default from Startup EndpointRouting user will come to this page, if a user is not login it will redirect to the login page

 [Authorize]
    public async Task<IActionResult> Index(bool? passIsChanged = null) // userId
    {
        if (passIsChanged != null)
        {
            ViewBag.isSuccessed = passIsChanged;
        }
        int id = Convert.ToInt32(User.Identity.Name);
        var user = _context.UserAccountTbs.FirstOrDefault(a => a.UserId == id);
        if (user == null)
        {
            return RedirectToAction("UserLogin", "Logins");
        }
            userprofile = new UserProfile
            {
                UserId = user.UserId,
                Name = users.FirstName,
            };


        return await Task.FromResult(View(userprofile));
    }

Here is My Login Controller code, if user is not login it return a new login model, if user is login it will check its password and user name then and validate it,

  public LoginsController(HoshmandDBContext context) : base(context)
    {
    }

    [HttpGet]
    public async Task<IActionResult> UserLogin()
    {
        return await Task.Run(() => View(new Login()));
    }

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> UserLogin([FromForm] Login currentUser)
    {
        if (ModelState.IsValid)
        {
            var properties = new AuthenticationProperties
            {
                IsPersistent = currentUser.RememberMe,
                AllowRefresh = false,
                ExpiresUtc = DateTimeOffset.UtcNow.AddDays(10)
            };

            UserAccountTb user = _context.UserAccountTbs.FirstOrDefault(a => a.UserName.Equals(currentUser.UserName));
            if (user == null)
            {
                TempData["UserLoginFailed"] = "Login Failed: Please Enter Correct Credential";
                return View();
            }
            else
            {
                // validate the password and login if not validate 
                show a message that enter correct password 
            }

First, you need to change SDK in.csproj file:

<TargetFramework>netcoreapp3.1</TargetFramework>

and remove this line:

<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />

Second, update the Nuget package you added to 3.1 corresponding version: 在此处输入图像描述

Then, you can change your Startup.cs:

  1. options.Cookie.Expiration is not supported in .net 3.1, you need to use options.ExpireTimeSpan to replace it.
  2. Change services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1) ; to services.AddMvc(); .
  3. The use of app.UseMvc(); to define endpoints will no longer be supported in .net 3.1. You need to use app.UseRouting(); and app.UseEndpoints(); .

In the end, your Startup.cs should look like this:

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)
        {
            var connection = Configuration.GetConnectionString("DBconnection");
            services.AddDbContext<HoshmandDBContext>(option => option.UseSqlServer(connection));
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath = "/Logins/UserLogin/";
                options.AccessDeniedPath = "/AccessDenied";
                options.ExpireTimeSpan = new TimeSpan(10, 00, 00);
            });

            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromHours(2);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;

            });

            services.ConfigureApplicationCookie(option =>
            {
                option.ExpireTimeSpan = TimeSpan.FromMinutes(540);
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("HasAccess", policy => policy.AddRequirements(new HasAccessRequirment()));
            });
            services.AddTransient<IAuthorizationHandler, HasAccessHandler>();
            services.AddTransient<IMvcControllerDiscovery, MvcControllerDiscovery>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseCookiePolicy();
            app.UseSession();

            app.UseEndpoints(endpoint => {
                endpoint.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=UserProfiles}/{action=Index}/{id?}");
            });
        }
    }

In addition, I added the [Authorize] attribute to the Index method of UserProfilesController to verify redirection:

public class UserProfilesController : Controller
    {
        [Authorize]
        public IActionResult Index()
        {
            return View();
        }
    }

LoginsController:

public class LoginsController : Controller
    {
        public IActionResult UserLogin()
        {
            return View();
        }
    }

Then run the project: 在此处输入图像描述

Right click on your project and select "Manage NuGet Packages", you can see the references of all your packages. Then select the corresponding package and update to the appropriate version: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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