asp.net-core - 对 Azure SQL 数据库的 .NET Core 控制器 API 调用在 localhost 中有效,但在已部署的 Azure Web App 中无效
问题描述
概括:
我有一个使用 React Web 应用程序模板作为前端的 .NET Core 项目。此应用使用 Entity Framework Core 连接到 Azure SQL 数据库。我使用 Db-Scaffold 命令生成我的模型(目前只有一个表),并创建了一个控制器来返回这个表。在本地,这可以正常工作,并且表(JSON)在 localhost/api/Users 中返回。但是,当我将网站部署到 Azure(CD 管道是 VS 2017 -> GitHub -> DockerHub -> Azure Web App)时,导航到mysite.azurewebsites.net/api/Users只会呈现我的应用程序的登录页面(React)。
尝试:
我努力了:
在 Azure 中添加连接字符串作为共享值(名为 DefaultConnection)
将 Azure Web App 的所有出站 IP 添加到 Azure SQL 白名单
在 Web 应用程序的控制台中运行以下命令
fetch('api/users')
这只是返回:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
我还尝试更改数据库值并刷新本地版本,以确保它不仅仅是一个缓存页面,并且确定这些更改已在本地反映出来。
我还在 Azure 的 Web 应用设置中将 ASPNETCORE_ENVIRONMENT 设置为生产。虽然当我转到错误消息时,页面(通过控制台)我得到了这个:
<h1 class="text-danger">Error.</h1> <h2 class="text-danger">An error occurred while processing your request.</h2> <p> <strong>Request ID:</strong> <code>0HLK3RLI8HD9Q:00000001</code> </p> <h3>Development Mode</h3> <p> Swapping to the <strong>Development</strong> environment displays detailed information about the error that occurred. </p> <p> <strong>The Development environment shouldn't be enabled for deployed applications.</strong> It can result in displaying sensitive information from exceptions to end users. For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong> and restarting the app. </p>
代码
用户控制器.cs
[Route("api/[controller]")]
public class UsersController : Controller
{
private readonly AccrubalanceDbContext _context;
public UsersController(AccrubalanceDbContext context)
{
_context = context;
}
// GET: api/values
[HttpGet]
public async Task<IEnumerable<Users>> Get()
{
return await _context.Users.ToListAsync();
}
应用设置.json
{
"ConnectionStrings": {
"DefaultConnection":<MyConnectionStringGoesHere>
},
index.js(以防 React 可能是路由问题)
const baseUrl = document.getElementsByTagName('base')
[0].getAttribute('href');
const rootElement = document.getElementById('root');
ReactDOM.render(
<BrowserRouter basename={baseUrl}>
<App />
</BrowserRouter>,
rootElement);
registerServiceWorker();
Startup.cs(Prod 中的 HTTP 路由可能存在问题?)
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)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
services.AddDbContext<AccrubalanceDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}
结论
总之,我需要此 API 调用才能在托管的 Azure Web 应用程序中工作,就像在我的本地计算机上一样。我知道我已经很接近了,因为我让它在本地工作,但是在通往 Azure 的路上我错过了一些东西。您可以提供的任何帮助或指示都会很棒:)
我对 SO 还是陌生的,所以我花时间尽力正确地格式化它。我愿意接受建设性的格式批评和建议,以帮助我改进。
编辑:
正如我之前提到的,我将 docker 用于 CD/CI。所以我在本地运行了我的 docker 容器,并且 api 在那里也不起作用。当我导航到应用程序主页时,Docker 在命令窗口中抛出此警告。
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
编辑 1 决心
我还发现这篇文章指出反应路由是一个问题。我在 Azure 应用程序中查看了 Kudo,但没有 web.config。可能会尝试添加,但我没有常规的 Windows UI,因为我的应用程序是 Linux 服务器。
容器构建的行为类似于 Azure 应用程序,可能不是 Azure 问题。仍然不确定为什么 docker 的行为与在 VS 中运行不同。
解决方案
解决方案:
Docker 显然存在一些问题。由于它变得更加令人头疼而不是帮助,因此我将其从部署管道中删除,并按照此处的说明进行操作。一旦我使用了这种部署方法,所有的 API 都可以正常工作。唯一的缺点是我必须在 Azure 中创建一个新应用程序。
推荐阅读
- amazon-web-services - 具有固定 IP 的 AWS 客户端 VPN
- c# - EpiServer 网站注销不再起作用
- pandas - 如何使用方法链接跨列使用 groupby 转换?
- google-apps-script - 如何在饼图中显示值 - Google Apps 脚本
- python-3.x - Pandas:如何计算 DateTime 索引
- nginx - Nginx 2 重写 2 例
- javascript - 导航栏不展开(React JS)
- reactjs - 样式(css)不适用于阴影 DOM 中的 React 应用程序
- regex - 替换为 regexp i Template Toolkit
- sparql - RDFlib 空白节点更新查询