首页 > 解决方案 > NETCore 2.1 - 无法访问 mssql 服务器/SqlExeption:无法打开登录请求的数据库“DbName”。登录失败

问题描述

我和我的团队正在 Visual Studio 2017 中开发一个项目,这是一个 NETCore 2.1 MVC Web 应用程序,这个项目有一个 MSSQL 数据库。我访问这个数据库没有问题,但是,我的同事遇到了以下异常:

SqlException:无法打开登录请求的数据库“MSSQL_DB”。登录失败。用户 '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));
            }
        }
    }
}

让我知道是否需要任何其他信息。

标签: c#sql-serverasp.net-coreasp.net-core-mvc

解决方案


.Wait();可能会导致死锁,从而导致超时。

参考Async/Await - 异步编程的最佳实践

如果在执行之前没有立即依赖异步调用完成,则无需等待即可离开它。

//...

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
}

推荐阅读