[英]How to move code in Startup.cs in ASP.NET Core 3.1 to ASP.NET Core 6?
[英]How to Convert Startup Code from asp.net core 2.1 to Startup Code asp.net Core 3.1
我想將我的項目從 asp.net 核心 2.1 升級到 asp.net 核心 3.1,我已經將 SDK 更改為 3.1,如下面的代碼,但我不知道根據啟動代碼 3.1 的需要在我的啟動代碼中更改什么
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
現在我想將我的啟動代碼從 asp.net core 2.1 更新為 asp.net core 3.1 請根據 asp.net core 3.1 的需要修改以下啟動代碼
這是我的啟動代碼版本 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 需要更新到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>
這是我的 UserProfile Controller 代碼,默認情況下從 Startup EndpointRouting 用戶會來到這個頁面,如果用戶沒有登錄它會重定向到登錄頁面
[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));
}
這是我的登錄 Controller 代碼,如果用戶未登錄,則返回新登錄 model,如果用戶已登錄,則將檢查其密碼和用戶名並進行驗證,
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
}
首先,您需要更改 SDK in.csproj 文件:
<TargetFramework>netcoreapp3.1</TargetFramework>
並刪除這一行:
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
二、更新你添加到3.1對應版本的Nuget package:
然后,您可以更改您的 Startup.cs:
options.Cookie.Expiration
,需要用options.ExpireTimeSpan
代替。services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
; 到services.AddMvc();
.app.UseMvc();
.net 3.1 將不再支持定義端點。 你需要使用app.UseRouting();
和app.UseEndpoints();
.最后,您的 Startup.cs 應該如下所示:
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?}");
});
}
}
另外,我在UserProfilesController
的Index
方法中添加了[Authorize]
屬性來驗證重定向:
public class UserProfilesController : Controller
{
[Authorize]
public IActionResult Index()
{
return View();
}
}
登錄控制器:
public class LoginsController : Controller
{
public IActionResult UserLogin()
{
return View();
}
}
右鍵單擊您的項目和 select “管理 NuGet 包”,您可以看到所有包的引用。 然后select對應package並更新到合適的版本:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.