简体   繁体   中英

SQL Server The server was not found or was not accessible

I am trying to create a new migration for a project, but I keep getting:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

I have the connection string in appsettings.json:

  "ConnectionStrings": {
    "DefaultConnection": "Server=xx.xx.xxx.206;Database=AngularASPNETCore2WebApiAuth; User ID = me; Password= not_pwd;Trusted_Connection=False;MultipleActiveResultSets=true"
  },

I tried:

  • confirmed the connection string is correct (it works in another project with a different database name)

  • confirmed that I can log into SQL with the credentials provided in the conn string

  • deleting everything from the Up method in the initial migration and re-running the update-database command. (same result)

What else can I try to troubleshoot this?

Inside Startup.cs the call to connect:

public void ConfigureServices(IServiceCollection services)
{
  // Add framework services.
  services.AddDbContext<ApplicationDbContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
          b => b.MigrationsAssembly("AngularASPNETCore2WebApiAuth")
          ));

  services.AddSingleton<IJwtFactory, JwtFactory>();

  // Register the ConfigurationBuilder instance of FacebookAuthSettings
  services.Configure<FacebookAuthSettings>(Configuration.GetSection(nameof(FacebookAuthSettings)));

  services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();

  // jwt wire up
  // Get options from app settings
  var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));

  // Configure JwtIssuerOptions
  services.Configure<JwtIssuerOptions>(options =>
  {
    options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
    options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
    options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
  });

  var tokenValidationParameters = new TokenValidationParameters
  {
    ValidateIssuer = true,
    ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],

    ValidateAudience = true,
    ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],

    ValidateIssuerSigningKey = true,
    IssuerSigningKey = _signingKey,

    RequireExpirationTime = false,
    ValidateLifetime = true,
    ClockSkew = TimeSpan.Zero
  };

  services.AddAuthentication(options =>
  {
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

  }).AddJwtBearer(configureOptions =>
  {
    configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
    configureOptions.TokenValidationParameters = tokenValidationParameters;
    configureOptions.SaveToken = true;
  });

  // api user claim policy
  services.AddAuthorization(options =>
  {
    options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
    });

  // add identity
  var builder = services.AddIdentityCore<AppUser>(o =>
  {
          // configure identity options
          o.Password.RequireDigit = false;
    o.Password.RequireLowercase = false;
    o.Password.RequireUppercase = false;
    o.Password.RequireNonAlphanumeric = false;
    o.Password.RequiredLength = 6;
  });
  builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);
  builder.AddEntityFrameworkStores<ApplicationDbContext>().AddDefaultTokenProviders();

  services.AddAutoMapper();
  services.AddMvc().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());
}

This error is usually resolved by the following:

  1. Ensure SQL Server Service is running
  2. Ensure that sql server is configured to permit remote connections.
  3. If a named instance, make sure SQL Server browser service is running
  4. Examine the SQL Server error log for messages confirming that SQL is listening on the expected network interfaces and ports (for example: 1433)
  5. Check to see in web.config or where the connection is coded if port is correct.
  6. Check firewall settings - add an exception in firewall for port

This post is quite useful and provides detailed information:

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

This question on Database Administrators has some good advice.

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