1

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>());
}
Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • Can you show the code of datacontext constructor where you have used the appsettings' connection string? Something could be missing there. – Prakash Dale Sep 11 '18 at 01:02
  • https://blogs.msdn.microsoft.com/sql_protocols/2008/04/30/steps-to-troubleshoot-sql-connectivity-issues/ BTW similar questions asked multiple times... – Mitch Wheat Sep 11 '18 at 01:13
  • FYI do not confuse the terms "database" with sql server instance (instance for short). You connect to an instance and then access a database within that instance. Your claim about "works in another project" does not add any useful information. Are you connecting to a default instance or a named instance? What values do you see/use in the SSMS connection dialog when you successfully connect (per your statement)? You posted a few weeks ago about the same problem but never responded. – SMor Sep 11 '18 at 14:23

1 Answers1

3

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.

Hannah Vernon
  • 3,367
  • 1
  • 26
  • 48
Gauravsa
  • 6,330
  • 2
  • 21
  • 30