0

As a precursor, I am using SQL Server Management Studio 18 for my Database and I am writing in Angular 11.

I am trying to write a GET method to pull my table dbo.Information from my database WeatherTemplate in SQL Server Management Studio 18. I'm continuing to recieve this error though and I am unable to resolve it:

System.Data.SqlClient.SqlException: '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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'

Win32Exception: The system cannot find the file specified.

With what I have written so far I should be able to use Postman and run my GET method to retrieve the table. My first assumption is I made a syntax error somewhere but I can't seem to find anything out of order. My code is below...

Controller Get Method

        [HttpGet]
        public JsonResult Get()
        {

            String query = @"select WeatherID, Date, TemperatureC, TemperatureF, Summary from dbo.Information";

            DataTable table = new DataTable();
            string sqlDataSource = _configuration.GetConnectionString("WeatherAppCon");
            SqlDataReader myReader;
            using(SqlConnection myCon=new SqlConnection(sqlDataSource))
            {
                myCon.Open();
                using (SqlCommand myCommand = new SqlCommand(query, myCon))
                {
                    myReader = myCommand.ExecuteReader();
                    table.Load(myReader); ;

                    myReader.Close();
                    myCon.Close();
                }
            }

            return new JsonResult(table);    
        }

appsettings.json

{
  "ConnectionStrings": {
    "WeatherAppCon": "Data Source=.;Initial Catalog=WeatherTemplate; Integrated Security=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;

namespace PROBLEM
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Enable CORS
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            });

            services.AddControllersWithViews();
            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            //JSON Serializer
            services.AddControllersWithViews()
                .AddNewtonsoftJson(options =>
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
                .AddNewtonsoftJson(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
                
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
               
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                  
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }
}
2
  • Your database is not "in SQL Server Management Studio". SSMS is just a client for connecting to and managing databases. It doesn't host databases itself. You've provided us a whole lot of code here, but none of it's really helpful. If your connection string isn't correct, or your database isn't set up to listen at the proper location, then none of that other code is going to matter. Commented Jun 7, 2021 at 15:22
  • What values do you supply in SSMS to connect to your sql server instance? Commented Jun 7, 2021 at 15:50

1 Answer 1

1

This error will happen due to wrong connection string

"ConnectionStrings": {
    "WeatherAppCon": "Data Source=.;Initial Catalog=WeatherTemplate; Integrated Security=true"
  }

It should be in below format

"ConnectionStrings": {
     "WeatherAppCon": "Server=<your server name>;Database=<your database name>;User Id=<your userId>;Password=<your password>;"
}
    
Sign up to request clarification or add additional context in comments.

1 Comment

I am glad to hear that your problem has been solved, you can click '✔' to mark your reply as an answer. It will also help others to solve the similar issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.