Angular 11:无法从 API 控制器连接到 SQL 服务器 -- GET 方法
Angular 11: Cannot Connect to SQL Server from API Controller -- GET Method
作为先驱,我正在为我的数据库使用 SQL Server Management Studio 18,并且我正在编写 Angular 11.
我正在尝试编写一个 GET 方法来从 SQL Server Management Studio 18 中的数据库 WeatherTemplate
中提取我的 table 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 方法来检索 table。我的第一个假设是我在某个地方犯了一个语法错误,但我似乎找不到任何有问题的地方。我的代码如下...
控制器获取方法
[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");
}
});
}
}
}
由于错误的连接字符串会发生此错误
"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>;"
}
作为先驱,我正在为我的数据库使用 SQL Server Management Studio 18,并且我正在编写 Angular 11.
我正在尝试编写一个 GET 方法来从 SQL Server Management Studio 18 中的数据库 WeatherTemplate
中提取我的 table 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 方法来检索 table。我的第一个假设是我在某个地方犯了一个语法错误,但我似乎找不到任何有问题的地方。我的代码如下...
控制器获取方法
[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");
}
});
}
}
}
由于错误的连接字符串会发生此错误
"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>;"
}