【问题标题】:Angular 11: Cannot Connect to SQL Server from API Controller -- GET MethodAngular 11:无法从 API 控制器连接到 SQL Server——GET 方法
【发布时间】:2021-08-24 15:58:57
【问题描述】:

作为先驱,我将 SQL Server Management Studio 18 用于我的数据库,并且我正在使用 Angular 11 编写代码。

我正在尝试编写一个 GET 方法来从 SQL Server Management Studio 18 中的数据库 WeatherTemplate 中提取我的表 dbo.Information。尽管我继续收到此错误,但我无法解决它:

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.

到目前为止,我应该能够使用 Postman 并运行我的 GET 方法来检索表。我的第一个假设是我在某处犯了语法错误,但我似乎找不到任何乱序的东西。我的代码在下面...

控制器获取方法

        [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");
                }
            });
        }
    }
}

【问题讨论】:

  • 您的数据库不在“SQL Server Management Studio 中”。 SSMS 只是一个用于连接和管理数据库的客户端。它本身不托管数据库。您在这里为我们提供了很多代码,但没有一个真正有用。如果您的连接字符串不正确,或者您的数据库未设置为在正确的位置进行侦听,那么其他代码都无关紧要。
  • 您在 SSMS 中提供哪些值来连接到您的 sql server 实例?

标签: asp.net sql-server angular visual-studio get


【解决方案1】:

由于连接字符串错误会发生此错误

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

应该是下面的格式

"ConnectionStrings": {
     "WeatherAppCon": "Server=<your server name>;Database=<your database name>;User Id=<your userId>;Password=<your password>;"
}
    

【讨论】:

  • 很高兴听到您的问题已经解决,您可以点击“✔”将您的回复标记为答案。它还将帮助其他人解决类似的问题。
猜你喜欢
  • 2023-01-18
  • 2019-05-29
  • 2016-12-26
  • 2021-03-22
  • 2016-07-02
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
相关资源
最近更新 更多