微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 11:无法从 API 控制器连接到 SQL Server——GET 方法

如何解决Angular 11:无法从 API 控制器连接到 SQL Server——GET 方法

作为先驱,我将 sql Server Management Studio 18 用于我的数据库,并使用 Angular 11 编写。

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

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

解决方法

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。