简体   繁体   English

将 asp.net web api 连接到 aws rds sql 服务器数据库

[英]Connecting asp.net web api to aws rds sql server database

I am trying to connect web api made in asp.net to sql server database provided by aws rds.我正在尝试将asp.net中制作的web api连接到aws rds提供的sql服务器数据库。 I have never used aws before so I am not really sure if I am missing something there.我以前从未使用过 aws,所以我不确定我是否遗漏了什么。 I have tried to do it but i get following message when I added migration and trying to update database (using EF core):我曾尝试这样做,但是当我添加迁移并尝试更新数据库(使用 EF 核心)时,我收到以下消息:

A.network-related or instance-specific error occurred while establishing a connection to SQL Server. A. 与 SQL 服务器建立连接时发生网络相关或特定于实例的错误。 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.验证实例名称是否正确以及 SQL 服务器是否配置为允许远程连接。 (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (提供商:命名管道提供商,错误:40 - 无法打开与 SQL 服务器的连接)

I have following code in my API:我的 API 中有以下代码:

Context class:上下文 class:

 public class TestContext : DbContext
    {
        public virtual DbSet<Fruit> Fruits { get; set; }

        public TestContext(DbContextOptions<TestContext> options) : base(options) { }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("server=<nameofserver>;user=<username>;password=<password>;database=<nameofdatabase>;"); // there i put data from my database hosted on aws
            }
        }

and in Program.cs:在 Program.cs 中:

builder.Services.AddDbContext<TestContext>(options =>
                options.UseSqlServer("server=<nameofserver>;user=<username>;password=<password>;database=<nameofdatabase>;"))// there i put data from my database hosted on aws1;

I know I should put connection string in appsettings.json but I believe that is not the case now.我知道我应该将连接字符串放在 appsettings.json 中,但我相信现在情况并非如此。 Why isn't the table being created in the database?为什么不在数据库中创建表? Should i enable/do sth on aws website?我应该在 aws 网站上启用/做某事吗? Or maybe the problem is in the code?或者问题出在代码中? How can I solve it?我该如何解决?

At the current time, you will find a similiar use case for AWS SDK for .NET .目前,您会发现 .NET 的AWS SDK的类似用例。

This current example shows you how to use the AWS SDK for .NET (v3) to create a REST service that lets you do the following:当前示例向您展示如何使用AWS SDK for .NET (v3)创建一个 REST 服务,让您可以执行以下操作:

  • Read, write, and update work items that are stored in an Amazon Aurora Serverless database.读取、写入和更新存储在Amazon Aurora Serverless数据库中的工作项。
  • Use Amazon Simple Email Service (Amazon SES) to send email reports of work items.使用 Amazon Simple Email Service (Amazon SES) 发送工作项的 email 报告。
  • Create an AWS Secrets Manager secret that contains database credentials and use it to authenticate calls to the database.创建一个包含数据库凭证的 AWS Secrets Manager 密钥,并使用它来验证对数据库的调用。 You can find this example in the AWS Code Library - which is the go to document for latest AWS SDK examples.您可以在AWS 代码库中找到此示例 - 这是 go 以记录最新的 AWS SDK 示例。

https://docs.aws.amazon.com/code-library/latest/ug/aurora_example_cross_RDSDataTracker_section.html https://docs.aws.amazon.com/code-library/latest/ug/aurora_example_cross_RDSDataTracker_section.html

I believe this example will be ported to SQL Server at some point.我相信这个例子会在某个时候移植到 SQL 服务器。

To connect to SQL Server, you need to supply your own connection details (unlike the Amazon Aurora Serverless database that needs other creds as discussed in the example.).要连接到 SQL 服务器,您需要提供自己的连接详细信息(与示例中讨论的需要其他凭据的Amazon Aurora Serverless数据库不同)。 Also note that SQL Server Does Not have a Service Client like Amazon Aurora Serverless does.另请注意,SQL 服务器没有像 Amazon Aurora Serverless 那样的服务客户端。

Also - make sure you set your inbound rules correctly.另外 - 确保正确设置入站规则。

https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSSecurityGroups.html https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Overview.RDSSecurityGroups.html

Once you set your inbound rules, set the user password, etc, the following C# should work.设置入站规则、设置用户密码等后,以下 C# 应该可以使用。

static void Main(string[] args)
        {
            try 
            { 
                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

                builder.DataSource = "<your_server.database.windows.net>"; 
                builder.UserID = "<your_username>";            
                builder.Password = "<your_password>";     
                builder.InitialCatalog = "<your_database>";
         
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    Console.WriteLine("\nQuery data example:");
                    Console.WriteLine("=========================================\n");
                    
                    connection.Open();       

                    String sql = "SELECT name, collation_name FROM sys.databases";

                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        using (SqlDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine("{0} {1}", reader.GetString(0), reader.GetString(1));
                            }
                        }
                    }                    
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("\nDone. Press enter.");
            Console.ReadLine(); 
        }
    }

It may or may not have anything to do with your connection string, but the very first thing you need to make sure of is that the server where your api/website is running has permissions to talk to your rds instance - by default it does not;它可能与您的连接字符串有任何关系,也可能没有任何关系,但您需要确保的第一件事是运行您的 api/网站的服务器有权与您的 rds 实例通信——默认情况下它没有; you will need a security group that specifically allows it before you do anything else (and don't accidentally make it public - you rds instance will get hammered by hackers trying t guess the password).在执行任何其他操作之前,您将需要一个专门允许它的安全组(并且不要不小心将其公开 - 您的 rds 实例会被试图猜测密码的黑客攻击)。

Easiest way to check is fire up SSMS or another such tool, and see if you can connect to RDS from the machine that runs the code - if you can't - nothing you do in your code will solve that.最简单的检查方法是启动 SSMS 或其他此类工具,看看是否可以从运行代码的机器连接到 RDS - 如果不能 - 你在代码中做的任何事情都无法解决这个问题。

Once you can connect from SSMS to RDS successfully, then you can play around with your connection string if it still is having problems.一旦您可以成功地从 SSMS 连接到 RDS,如果连接字符串仍然有问题,您可以尝试使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM