簡體   English   中英

從反應前端與 ASP.NET Core Web API 在同一個遠程主機面板上進行通信

[英]Communicating from react front-end with ASP.NET Core Web API on the same remote hosting panel

我有一個獨立的反應前端和 ASP.NET 核心 Web API(后端)在本地主機上工作和通信正常。 我在 webApi 項目中創建了 ClientApp 文件夾,並在其中復制了整個反應應用程序。 然后按照@Ringo 對類似問題的回答在這里

我將前端和后端的 url 從https://localhost:3000更改為https://www.virtualcollege.pk

但它不適用於遠程這里是鏈接

program.cs 是:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                        .UseUrls("https://www.virtualcollege.pk");
                });
    }
}

啟動.cs:

using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Services;


namespace WebApi
{
    public class Startup
    {
        private readonly IWebHostEnvironment _env;
        private readonly IConfiguration _configuration;

        public Startup(IWebHostEnvironment env, IConfiguration configuration)
        {
            _env = env;
            _configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // use sql server db in production and sqlite db in development
            
          
            services.AddDbContext<DataContext>();
            
            services.AddDbContext<CourseDbContext>();
            services.AddCors();
           
            services.AddControllers();
            
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            // configure strongly typed settings objects
            var appSettingsSection = _configuration.GetSection("AppSettings");
            services.Configure<AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get<AppSettings>();
            var key = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
                        var userId = int.Parse(context.Principal.Identity.Name);
                        var user = userService.GetById(userId);
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return Task.CompletedTask;
                    }
                };
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            // configure DI for application services
            services.AddScoped<IUserService, UserService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext dataContext)
        {
           
            // migrate any database changes on startup (includes initial db creation)
            dataContext.Database.Migrate();
     
            app.UseRouting();

            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();
          
            app.UseEndpoints(endpoints => endpoints.MapControllers());
            //add this
            app.UseStaticFiles();
            if (!env.IsDevelopment())
            {
                app.UseSpaStaticFiles();
            }


            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA
                // see https://go.microsoft.com/fwlink/?linkid=864501
                spa.Options.SourcePath = "ClientApp";
                if (_env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }
}

前端webpack.config.json為:

var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    
    mode: 'development',
    resolve: {
        extensions: ['.js', '.jsx']
    },
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader'
            }
        ]
    },
    plugins: [new HtmlWebpackPlugin({
        template: './src/index.html'
    })],
    devServer: {
        historyApiFallback: true
        
    },
    output:{
        filename: '[name]-bundle.js',
    },
    externals: {
        // global app config object
        
        config: JSON.stringify({
            apiUrl: 'https://www.virtualcollege.pk'
        })
    }
}

我嘗試了很多端口,無論是前端工作還是后端。如果我使用以下web.config文件后端工作但沒有index.html由服務器返回。 web.config 在這里:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<location path="." inheritInChildApplications="false">
    <system.webServer>
   
     <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      </handlers>
            <aspNetCore processPath=".\WebApi.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="outprocess" /> 

        <httpErrors>
            <remove statusCode="502" subStatusCode="-1" />
            <remove statusCode="501" subStatusCode="-1" />
            <remove statusCode="500" subStatusCode="-1" />
            <remove statusCode="412" subStatusCode="-1" />
            <remove statusCode="406" subStatusCode="-1" />
            <remove statusCode="405" subStatusCode="-1" />
            <remove statusCode="404" subStatusCode="-1" />
            <remove statusCode="403" subStatusCode="-1" />
            <remove statusCode="401" subStatusCode="-1" />
            <remove statusCode="400" />
            <error statusCode="400" path="D:\inutpub\virtualcollege.pk\error_docs\bad_request.html" />
            <remove statusCode="407" />
            <error statusCode="407" path="D:\inutpub\virtualcollege.pk\error_docs\proxy_authentication_required.html" />
            <remove statusCode="414" />
            <error statusCode="414" path="D:\inutpub\virtualcollege.pk\error_docs\request-uri_too_long.html" />
            <remove statusCode="415" />
            <error statusCode="415" path="D:\inutpub\virtualcollege.pk\error_docs\unsupported_media_type.html" />
            <remove statusCode="503" />
            <error statusCode="503" path="D:\inutpub\virtualcollege.pk\error_docs\maintenance.html" />
            <error statusCode="401" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\unauthorized.html" />
            <error statusCode="403" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\forbidden.html" />
            <error statusCode="404" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\not_found.html" />
            <error statusCode="405" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\method_not_allowed.html" />
            <error statusCode="406" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\not_acceptable.html" />
            <error statusCode="412" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\precondition_failed.html" />
            <error statusCode="500" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\internal_server_error.html" />
            <error statusCode="501" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\not_implemented.html" />
            <error statusCode="502" prefixLanguageFilePath="" path="D:\inutpub\virtualcollege.pk\error_docs\bad_gateway.html" />
        </httpErrors>
    </system.webServer>
    </location>
</configuration>

如果我使用默認的web.config文件已經存在 httpdocs 前端工作但 api 調用不起作用。

在此先感謝您的幫助,我在使用 url: https:localhost:4000在 localhost 上啟動時添加了屏幕截圖,它在顯示以下錯誤后開始正常工作: 本地主機上的屏幕截圖 但是當部署到遠程服務器時,它顯示: www.virtualcollege.pk is currently unable to handle this request.http error 500這里是啟動設置。json:

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iis": {
      "applicationUrl": "http://localhost/WebApi",
      "sslPort": 0
    },
    "iisExpress": {
      "applicationUrl": "http://localhost:61907/",
      "sslPort": 0
    }
  },
  "profiles": {
    "Development": {
      "commandName": "Project",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

我正在分享,以便對其他人有所幫助,經過幾天的嘗試和錯誤,我發現應該采取一個額外的步驟來將reactasp.net webapi 也就是說,編輯.cspoj文件並在其中添加一些額外的代碼。 因此,我使用visual studio template中的 asp.net 核心應用程序創建了一個新的反應,並打開了.csproj文件並將其中的內容復制到我的項目.csproj中。 現在它工作正常。 這是鏈接:這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM