ASP.NET CORE 5.0 Web API 在 IIS Express 上工作,但在 IIS 10 上托管时给出 404 [英] ASP.NET CORE 5.0 Web API works on IIS Express but gives 404 when hosted on IIS 10

查看:71
本文介绍了ASP.NET CORE 5.0 Web API 在 IIS Express 上工作,但在 IIS 10 上托管时给出 404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个解决方案中有一个 WEB APP 和一个 Web API 项目.最近我们在 API 项目中添加了 Swashbuckle 和 Swagger UI.现在,当使用 IIS Express 在 VS 中运行表单(调试/不调试)时,Web API 工作正常,Swagger.json 是可访问的,Swagger UI 在 https://localhost:/API/docs/index.html 上提供并尝试输出 https://localhost:/API/docs/,返回有效输出.

I have a WEB APP and a Web API project within a single solution. Recently we added Swashbuckle and Swagger UI to the API Project. Now, The Web API works fine when run form within VS (debug / without debugging) using IIS Express, Swagger.json is accessbile, Swagger UI is served on https://localhost:/API/docs/index.html and on trying it out https://localhost:/API/docs/, returns valid output.

但是,在发布并部署到 IIS 站点后,它返回 404 错误.Swagger.json 已形成,Swagger UI 在 https://domain:/API/docs/index.html 上正确提供,但在尝试时 https://domain:/API/docs/以 404 响应.(DNS映射正确).

However, after publishing and deploying onto IIS Site, it returns a 404 error. The Swagger.json is formed, the Swagger UI is served correctly on https://domain:/API/docs/index.html but when trying out https://domain:/API/docs/ responds back with 404. (DNS is mapped correctly).

IIS 10.0 详细错误 - 404.0 - 未找到

IIS 10.0 Detailed Error - 404.0 - Not Found

Detailed Error Information: 
Module        IIS Web Core 
Notification MapRequestHandler 
Handler       StaticFile 
Error Code   0x80070002 
Requested URL https://localhost:<port>/Rejected-By-UrlScan?~/API/docs/<command> 
Physical Path <path>iis\abc\Rejected-By-UrlScan 
Logon Method Anonymous 
Logon User      Anonymous

通过 CLI 成功发布

Publishing through CLI successful

dotnet publish -c release -r win-x64 --self-contained false

Startup.cs

  public void ConfigureServices(IServiceCollection services)
            {
            
 
 
 
 
 
 
 
 services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
            .AddCertificate();

            services.Configure<ApplicationSetting>(Configuration.GetSection("ApplicationSettings"));
            services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
                                                                    .AllowAnyMethod()
                                                                     .AllowAnyHeader()));


            services.AddControllers()
                    .ConfigureApiBehaviorOptions(options =>
                    {
                        options.SuppressModelStateInvalidFilter = true;
                    });


            services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                    .AddNewtonsoftJson(options =>
                    {
                        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    });

            services.AddMvcCore()
                    .AddApiExplorer();

            abcDBContext.ConnectionString = Configuration.GetConnectionString("abcDBContext");

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = API",
                    Description = "Web API",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact = new OpenApiContact
                    {
                        Name = "ABC Support",
                        Email = string.Empty,
                        Url = new Uri("https://example.com/"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = new Uri("https://example.com/license"),
                    }
                });

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

            DependencyInjections.Dependency(services,Configuration);
             
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

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

            if (env.IsProduction() || env.IsStaging())
            {
                app.UseExceptionHandler("/Error/index.html");
            }

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger(c =>
            {
                c.RouteTemplate = "docs/{documentName}/swagger.json";
            });

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.RoutePrefix = "docs"; 
                c.SwaggerEndpoint("v1/swagger.json", "v1");

                // custom CSS
                c.InjectStylesheet("/swagger-ui/custom.css");
            });

            app.Use(async (ctx, next) =>
            {
                await next();
                if (ctx.Response.StatusCode == 204)
                {
                    ctx.Response.ContentLength = 0;
                }
            });


            app.UseCors(builder =>
            builder.WithOrigins(Configuration["ApplicationSettings:Client_URL"].ToString())
            .AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod()
            );

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();
            app.UseAuthentication();

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

            app.UseCors();

        }

LaunchSettings.json

LaunchSettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:2618",
      "sslPort": 44311
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "docs",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Web.API": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "docs",
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

操作系统:Windows 10 最新版本 x64

OS : Windows 10 latest version x64

IIS 站点(使用相同的应用程序池)

IIS Site (using same application pool)

应用程序池详情

IIS 站点

推荐答案

我通过卸载 URLScan 3.1 解决了这个问题,基于 (链接)由 Lex Li 共享="https://forums.asp.net/p/2172288/6325066.aspx?p=True&t=637412569442538273" rel="nofollow noreferrer">这里

I solved this by uninstalling URLScan 3.1, based on the (Link) shared by Lex Li and from here

这篇关于ASP.NET CORE 5.0 Web API 在 IIS Express 上工作,但在 IIS 10 上托管时给出 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆