我已将 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) );
});
现在应该可以工作了。
演示
关于mysql - 连接到 Azure 应用服务中的应用内 MySQL 时出现套接字错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57996916/