简体   繁体   English

从 React 应用程序访问 asp.net 核心 api(均已容器化)

[英]Accessing asp.net core api from react app (both containerized)

So I have a containerized app which consists of react + asp.net core + keycloak + nginx.所以我有一个容器化的应用程序,它由 react + asp.net core + keycloak + nginx 组成。

I don't want to publish the port of the API to the inte.net, I only want it to be accessible in the containers'.network.我不想将 API 的端口发布到 inte.net,我只希望它可以在容器的.network 中访问。

But I can't manage to make my API calls from the React app.但是我无法通过 React 应用拨打 API 电话。

Right now I'm doing them here:现在我在这里做它们:

https://localhost:7266

docker-compose of asp.net core container asp.net核心容器的docker-compose

mediere-api:
    container_name: best-asp.net
    image: ${DOCKER_REGISTRY-}mediere-api
    build:
      context: ..
      dockerfile: Dockerfile
    env_file:
        - .env
    depends_on:
            - db
    expose:
      - "7266"
    volumes:
        - ../certs/certificate.pfx:/etc/https/certs

dockerfile of it其中dockerfile

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["mediere-API.csproj", "."]
RUN dotnet restore "mediere-API.csproj"
COPY . .
WORKDIR "/src/"
RUN dotnet build "mediere-API.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "mediere-API.csproj" -c Release -o /app/publish 

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "mediere-API.dll"]

appsettings.json应用程序设置.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    deleted
  }
}

launchSettings.json launchSettings.json

{
  "profiles": {
    "mediere_API": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      },
      "applicationUrl": "https://localhost:7266",
      "dotnetRunMessages": true
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },
    "Docker": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
      "publishAllPorts": true,
      "useSSL": true
    }
  }
}

.env .env

#ASP.Net core
ASPNETCORE_STATICWEBASSETS="/app/bin/Debug/net6.0/mediere-api.staticwebassets.runtime.CT.json"
ASPNETCORE_ENVIRONMENT=Production
ASPNETCORE_URLS=https://localhost:7266

Proogram.cs程序.cs

using mediere_API.DataLayer;
using mediere_API.DataLayer.Repository.Implementations;
using mediere_API.DataLayer.Repository.Interfaces;
using mediere_API.Extensions;
using mediere_API.Middleware;
using mediere_API.Processors.Implementations;
using mediere_API.Processors.Interfaces;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

//Servicii
builder.Services.AddControllers();
builder.Services.ConfigureSwagger();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddRouting(options => options.LowercaseUrls = true);

builder.Services.AddRepositories();
builder.Services.AddProcessors();

//UnitsOfWork
builder.Services.AddScoped<ISchemaUnitOfWork, SchemaUnitOfWork>();
builder.Services.AddScoped<IMainUnitOfWork, MainUnitOfWork>();

//AutoMapper
builder.Services.AddAutoMapper(typeof(Program));
//Keycloak
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
    {
        o.MetadataAddress = "https://keycloak:8443/auth/realms/best-realm/.well-known/openid-configuration";
        o.Authority = "https://keycloak:8443/auth/realms/best-realm";
        o.Audience = "account";
        o.RequireHttpsMetadata = false;
    });
//CORS
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(
        policy =>
        {
            policy.AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .WithExposedHeaders("FileName");
        });
});

builder.Services.AddDbContext<EfDbContext>();
builder.Services.AddDbContext<SchemaEfDbContext>();


var app = builder.Build();
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();

app.UseMiddleware<SchemaHandlingMiddleware>();

app.UseCors();

app.UseAuthorization();

app.MapControllers();

app.Run();

With these settings, my API calls don't seem to reach the Docker container.使用这些设置,我的 API 调用似乎没有到达 Docker 容器。 I get:我得到:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:7266/api/proiecte. (Reason: CORS request did not succeed). Status code: (null)

status code null means that the container couldn't be reached I think.状态码 null 意味着我认为无法到达容器。

So what's wrong with my settings?那么我的设置有什么问题吗?

How should I do my API calls to the ASP container from docker in order for them to work?我应该如何从 docker 对 ASP 容器进行 API 调用才能使它们工作?

Thanks.谢谢。

  • Same Origin serving approach using reverse proxy:使用反向代理的同源服务方法:

    You should reverse proxy your API inside your nginx configuration.您应该在 nginx 配置中反向代理您的 API。 Something like this:像这样:

    nginx.conf: nginx.conf:

    location / proxy_pass: TO_YOUR_REACT_APP or: SERVER_YOUR_REACT_APP_STATIC_FILES位置/proxy_pass:TO_YOUR_REACT_APP 或:SERVER_YOUR_REACT_APP_STATIC_FILES

    location /api proxy_pass: TO_YOUR_API位置/api proxy_pass: TO_YOUR_API

    This approach makes your API and REACT app to be at the same origin.这种方法使您的 API 和 REACT 应用程序处于同一来源。 So there will be no CORS error.所以不会出现CORS错误。

  • Enabling CORS for requests that you are sending via browser.为您通过浏览器发送的请求启用 CORS。 Please share a screen shot from your browser console error in order th help you with.请分享您的浏览器控制台错误的屏幕截图,以便帮助您解决问题。

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

相关问题 从 React Native 访问 ASP.NET Core 2.1 Web API 时“无法对 HTTPS 连接进行身份验证” - 'Failed to authenticate HTTPS connection' while accessing ASP.NET Core 2.1 Web API from React Native 从 ASP.NET 核心应用程序访问 Azure KeyVault 中的证书 - Accessing certificate in Azure KeyVault from ASP.NET Core app ASP.Net核心API访问HttpRequestMessage - ASP.Net Core API Accessing HttpRequestMessage 为 docker 容器化 ASP.NET 核心应用程序启用 CORS 的最佳实践是什么 - What are the best practices to enable CORS for docker containerized ASP.NET core app 将表单数据从 React 发送到 ASP.NET Core API - Send form data from React to ASP.NET Core API 从ASP.NET核心应用程序无法进行API发布调用 - API Post call not working from ASP.NET core app 从控制台应用程序启动 ASP.NET Core Web API - Start ASP.NET Core Web API from a Console App 在 ASP.NET 内核 Web API 中访问和使用 UserClaims - Accessing and using UserClaims in ASP.NET Core Web API 访问在 Linux VPS 上运行的 ASP.Net Core MVC 应用程序 - Accessing ASP.Net Core MVC app running on Linux VPS 从ASP.NET Core Web App访问类库中的实体框架 - Accessing Entity Framework In Class Library From ASP.NET Core Web App
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM