首页 > 解决方案 > 对 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)。

尝试:

我努力了:

代码

用户控制器.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 中运行不同。

标签: asp.net-corereact-routerazure-sql-databaseazure-web-app-serviceasp.net-core-webapi

解决方案


解决方案:

Docker 显然存在一些问题。由于它变得更加令人头疼而不是帮助,因此我将其从部署管道中删除,并按照此处的说明进行操作。一旦我使用了这种部署方法,所有的 API 都可以正常工作。唯一的缺点是我必须在 Azure 中创建一个新应用程序。


推荐阅读