繁体   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