mysql - 连接到 Azure 应用服务中的应用内 MySQL 时出现套接字错误

标签 mysql asp.net azure asp.net-core

我已将 ASP.NET Core 2.2 Web API 应用程序部署到 Azure 应用服务。我有一个应用内 MySQL 作为应用服务的一部分。当我调用 API 时,出现以下错误:

"ExtendedSocketException: An attempt was made to access a socket in a way forbidden by its access permissions 127.0.0.1:3306"

我四处寻找解决方案,发现了这个:Access denied error while connecting to MySQL in App in Azure App Service

但是上面建议的修复并没有解决问题。

我还尝试了各种连接字符串,它们都导致了相同的异常。这是我目前拥有的:

Server=localhost;Port=3306;Database=dbname;Uid=username;Pwd=password

所以,我的问题是:我应该怎样做才能使我的 ASP.NET Core API 连接到我的应用内 MySql 数据库?

PS1:有很多文章介绍了如何解决 Azure MySql DB 的连接问题(例如设置防火墙访问等),但没有介绍 In App MySQL 的连接问题。

最佳答案

首先,您无法通过appsettings.json配置连接字符串。 Azure InApp MySQL 连接字符串是通过环境变量自动配置的:MYSQLCONNSTR_localdb

根据the docs :

The Configuration API has special processing rules for four connection string environment variables involved in configuring Azure connection strings for the app environment. Environment variables with the prefixes shown in the table are loaded into the app if no prefix is supplied to AddEnvironmentVariables.

简而言之,您需要通过以下方式获取预定义的ConnectionString:

var conn = Configuration.GetConnectionString("localdb");

此外,Azure InApp MySQL ConnectionString 不是 Standard MySQL ConnectionString :

Database=localdb;Server={host_like_127.0.0.1}:{port_like_52841};Uid={azure};Pwd={random}

换句话说,默认的 ConnectionString 尚未准备好在 C# 中使用。

如何连接InApp MySQL

为了将 InApp MySQL 与 ASP.NET Core 连接,我们需要在将其传递给 UseMySQL(conn) 之前对其进行规范化。这是我的脏代码,用于标准化默认的 InApp ConnectionString:

private string NormalizeAzureInAppConnString(string raw) {
    string conn = string.Empty;
    try
    {
        var dict =
             raw.Split(';')
                 .Where(kvp => kvp.Contains('='))
                 .Select(kvp => kvp.Split(new char[] { '=' }, 2))
                 .ToDictionary(kvp => kvp[0].Trim(), kvp => kvp[1].Trim(), StringComparer.InvariantCultureIgnoreCase);
        var ds = dict["Data Source"];
        var dsa = ds.Split(":");
        conn = $"Server={dsa[0]};Port={dsa[1]};Database={dict["Database"]};Uid={dict["User Id"]};Pwd={dict["Password"]};";
    }
    catch {
        throw new Exception("unexpected connection string: datasource is empty or null");
    }
    return conn;
}

然后您可以按如下方式注册 DbContext:

services.AddDbContext<AppDbContext>(options =>{
    var conn = Configuration.GetConnectionString("localdb");
    options.UseMySql( NormalizeAzureInAppConnString(conn) );
});

现在应该可以工作了。

演示

enter image description here

关于mysql - 连接到 Azure 应用服务中的应用内 MySQL 时出现套接字错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57996916/

相关文章:

mysql - 在sql查询中从另一个表引用表名

c# - 在一个可靠的解决方案中集成用 Python 编写的测试和用 C# 编写的测试

c# - 如何仅为按钮事件设置进度条

azure - 无法使用 Azure 资源管理器模板的资源函数

mysql - 如何在总和中显示另一个值而不是 NULL?

javascript - 关于 PayPal Pro 付款

mysql - 由 : java. sql.SQLSyntaxErrorException : [. ..] 版本引起,以便在第 1 行 'order (id)' 附近使用正确的语法

javascript - 信号器框架何时调用 Signalr IUserIdProvider 的方法 GetUserId

azure - 将包含特殊字符的标签发送到 Azure 通知中心

Azure 虚拟机卡在 "starting"