将.net Core 3.1 Web API发布到远程服务器时遇到问题

如何解决将.net Core 3.1 Web API发布到远程服务器时遇到问题

发布后,我在远程服务器上运行asp.net core 3.1 Web API时遇到问题。该API在我的PC上运行良好,但是当我发布该API时,所有API端点都返回错误404。我昂首阔步的文档页面swagger / index.html也返回相同的错误。

下面是Program.cs代码

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>();
            });
}

我的启动cs文件如下

public class Startup
{
    private readonly IWebHostEnvironment _env;
    private readonly IConfiguration _configuration;
    //public static IMvcBuilder ConfigureApiBehaviorOptions(this IMvcBuilder builder,Action<ApiBehaviorOptions> setupAction);

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

    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)
    {
        try
        {
            // use sql server db in production and sqlite db in development
            //if (_env.IsProduction())
            //    services.AddDbContext<DataContext,SqlDataContext>();
            //else
            //    services.AddDbContext<DataContext,SqliteDataContext>();

            //services.AddDbContext<DataContext,SqlDataContext>();
            services.AddDbContext<DataContext,SqlDataContext>
            (options => options.UseSqlServer(Configuration.GetConnectionString("SQLServerdb")));

            services.AddCors();
            services.AddControllers();
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

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

            // enabling API documentation
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Version = "v1",Title = "x",Description = "x",TermsOfService = null,Contact = new Microsoft.OpenApi.Models.OpenApiContact()
                    {
                        Name = "x",Email = "x",Url = null
                    }
                });

                    // Set the comments path for the Swagger JSON and UI.
                    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory,xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            // enabling Cookies
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
            }).AddCookie("Cookies",options =>
            {
                options.Cookie.Name = globals.APISessionKey;
                options.Cookie.SameSite = SameSiteMode.None;
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin = redirectContext =>
                    {
                        redirectContext.HttpContext.Response.StatusCode = 401;
                        return Task.CompletedTask;
                    }
                };
            });

            // 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 theContext = context.HttpContext;
                        var userId = int.Parse(context.Principal.Identity.Name);
                        var user = userService.GetById(context.HttpContext,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
                };
            });


            // custom validation responses CustomBadRequest
            //services.Configure<ApiBehaviorOptions>(a =>
            //{
            //    a.InvalidModelStateResponseFactory = context =>
            //    {
            //        var problemDetails = new CustomBadRequest(context);

            //        return new BadRequestObjectResult(problemDetails)
            //        {
            //           // ContentTypes = { "application / problem + json","application / problem + xml" } // these requires cross origin resource what what (cors)
            //        };
            //    };
            //});
        }
        catch (Exception ex)
        {
            Console.WriteLine("ConfigureServices _ERROR: " + ex.Message);
        }
    }

    // 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)
    {
        try
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            dataContext.Database.Migrate();

            app.UseHttpsRedirection();

            app.UseRouting();

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

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // Enable middle ware to serve swagger-ui (HTML,JS,CSS etc.),specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("../swagger/v1/swagger.json","My API V1 (RELEASE)");
                    //c.SwaggerEndpoint("/swagger/v1/swagger.json","My API V1 (DEBUG)");

                    /*To serve the Swagger UI at the app's root (http://localhost:<port>/),set the RoutePrefix property to an empty string:
                    c.SwaggerEndpoint("/swagger/v1/swagger.json","My API V1");
                    c.RoutePrefix = string.Empty;*/
            });

            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}

            //app.UseHttpsRedirection();

            //app.UseRouting();

            //app.UseAuthorization();

            //app.UseEndpoints(endpoints =>
            //{
            //    endpoints.MapControllers();
            //});
        }
        catch (Exception ex)
        {
            Console.WriteLine("Configure _ERROR: " + ex.Message);
        }
    }
}
}

有什么我想念的东西吗?我的API与blazor服务器应用程序使用相同的解决方案,该应用程序在API无法正常运行的同一服务器上运行良好。

我曾尝试自行修复该问题并在互联网上进行搜索,但没有找到任何可以帮助我解决此问题的方法。非常感谢您的帮助。

解决方法

项目的Swagger设置没有问题。看来您正在将DotNet Core应用程序(Core Web API和Blazor服务应用程序)部署到IIS Web服务器。
一般来说,如果这些应用程序在本地正常运行,但在远程Web服务器中返回HTTP错误。托管环境可能配置不正确。 例如,托管DotNet Core应用程序时,需要以下IIS托管捆绑软件。
enter image description here
下载URL(直接下载)。
https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-aspnetcore-3.1.7-windows-hosting-bundle-installer
此外,应该使用IUSR帐户或Everyone帐户正确访问发布位置,即网站根目录。它取决于应用程序池标识的帐户。
enter image description here
随时让我知道问题是否仍然存在。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-