c# - NETCore 2.1 - 无法访问mssql服务器/SqlExeption : Cannot open database "DbName" requested by the login.登录失败

标签 c# sql-server asp.net-core asp.net-core-mvc

我和我的团队正在 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/

相关文章:

c# - 对于存储在 ini 文件中的信息来说,什么是好的映射器模式?

c# - 需要专家对 .net 应用程序最快通信的评论

c# - TypedActor 与 ReceiveActor?

c# - 如何在 Roslyn 中查找具有特定名称的字段类型

java - JPA Join 打印多个结果

sql-server - PowerBI 无法使用专用端点连接到 Azure SQL

c# - 在 asp.net-core MVC 应用程序上需要 DocumentDB

c# - 带有 Api 版本控制的 CreatedAtRoute

sql-server - 用于跟踪随时间推移的进度的数据库设计

c# - Entity Framework SaveChangesAsync 不更新数据库