我和我的团队正在 Visual Studio 2017 中开发一个项目,该项目是 NETCore 2.1 MVC Web 应用程序,该项目有一个 MSSQL 数据库。我访问此数据库没有问题,但是,我的同事遇到以下异常:
SqlException: Cannot open database "MSSQL_DB" requested by the login. The login failed. Login failed for user 'DESKTOP-machinename\windowsLogin'.
在网络上研究问题后,我发现大多数情况下问题是 ASP.NET 未配置为使用 Windows 身份验证。因此,我还进行了以下更改,但仍然存在相同的问题。
将 web.config 文件添加到项目中:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authentication mode="Windows"/>
</system.web>
</configuration>
通过添加 Integrated Security=False 修改了 appsettings.json:
"ConnectionStrings": {
"DbConnection": "Server=(localdb)\\mssqllocaldb;Database=MSSQL_DB;Integrated Security=False;Trusted_Connection=True;MultipleActiveResultSets=true"
启动设置.json:
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:43064",
"sslPort": 44395
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"NETCore2IdentityWebApp_v3": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
也许值得一提的是,在Configure方法的末尾,有一个方法检查是否有任何用户角色添加到角色表中,如果没有,则添加它们。每当异常发生时,它都会发生在我们执行此方法的行上。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider servpro)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseDefaultFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "searchresults",
template: "searchresults",
defaults: new { controller = "SearchResults", action = "SearchResults" });
routes.MapRoute(
name: "hotel",
template: "hotel",
defaults: new { controller = "Hotel", action = "Hotel" });
routes.MapRoute(
name: "hotels",
template: "hotels",
defaults: new { controller = "Hotels", action = "Hotels" });
routes.MapRoute(
name: "contact",
template: "contact",
defaults: new { controller = "Contact", action = "Contact" });
routes.MapRoute(
name: "booking",
template: "booking",
defaults: new { controller = "Booking", action = "Booking" });
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
InitRoles.CreateRoles(servpro).Wait(); //Exception happens here
}
以及InitRoles
类:
public class InitRoles
{
public static async Task CreateRoles(IServiceProvider serviceProvider)
{
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Standard" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
}
}
如果需要任何其他信息,请告诉我。
最佳答案
.Wait();
可能会导致死锁,从而导致超时。
引用Async/Await - Best Practices in Asynchronous Programming
如果没有任何内容立即依赖于异步调用在执行之前完成,则无需等待。
//...
InitRoles.CreateRoles(servpro);
您也可以执行异步事件处理程序,在其中等待调用,然后调用依赖于首先完成的代码的内容。
private event EventHandler creatingRoles = delegate { };
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider servpro) {
//...omitted for brevity
EventHandler handler = null;
handler = async (sender, args) => {
creatingRoles -= handler; //unsubscribe from event
await InitRoles.CreateRoles(servpro);
//...code dependent on the above completing
//...
};
creatingRoles += handler; //subscribe to event
creatingRoles(this, EventArgs.Empty); //raise event
}
关于c# - NETCore 2.1 - 无法访问mssql服务器/SqlExeption : Cannot open database "DbName" requested by the login.登录失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53744346/