简体   繁体   English

ASP.NET Core(HttpSys)路由在本地工作,但在部署时不工作

[英]ASP.NET Core (HttpSys) Routing works locally but not when deployed

For some reason when I'm running my ASP.NET Core API using HttpSys on a windows server (through service fabric) the routing doesn't work whereas locally everything works. 出于某种原因,当我在Windows服务器上使用HttpSys运行我的ASP.NET核API(通过服务结构)时,路由不起作用,而本地一切正常。 The thing is that the middleware works fine, so I know that the request is being processed but it's never able to hit any controller, it just defaults to my app.run("Some 404 response") 404 middleware. 问题是中间件工作正常,所以我知道请求正在处理但它永远不能打到任何控制器,它只是默认为我的app.run("Some 404 response") 404中间件。 Some of my code: 我的一些代码:

Startup.cs Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    #region IOC
    //ommitted
    #endregion 

    services.AddAutoMapper(typeof(SomeModel));

    services.AddCors(c => 
    {
        c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
    });

    services.AddDbContext<SomeContext>(options => options.UseSqlServer(_configuration.GetConnectionString("Dev")));

    services.AddMvc().AddFluentValidation();
}        

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        IdentityModelEventSource.ShowPII = true;
    }

    //Eliminating that auth is the problem
    //app.UseAuthentication(); 

    if (env.IsProduction())
    {
        app.UseHsts();
        app.UseHttpsRedirection();
    }

    app.UseCors("AllowOrigin");
    app.UseMvcWithDefaultRoute(); //tried this instead of below. No luck

    //app.UseMvc();

    app.Use((context, next) =>
    {
        if (context.Request.Path.Value == "" || context.Request.Path.Value == "/")
        {
            context.Response.ContentType = "text/plain";
            return context.Response.WriteAsync("We're running!");
        }

        return next.Invoke();
    });

    app.Run(context =>
    {
        context.Response.StatusCode = 404;
        context.Response.ContentType = "application/json";

        return context.Response.WriteAsync("{ \"message\": \"Not found\" }");
        });
    }
}

Program.cs: Program.cs中:

public static void Main(string[] args)
{
    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<SomeContext>();
            DbInitializer.Initialize(context);
        }
        catch (Exception ex)
        {
            logger.Error(ex, "An error occured while seeding the database");
        }
    }

    host.Run();
}
public static IWebHost CreateWebHostBuilder(string[] args)
{
    IHostingEnvironment env = null;

    var builder = 
        WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
           env = hostingContext.HostingEnvironment;
        })
        .UseHttpSys(options =>
        {
            if (!env.IsDevelopment())
            {
                options.UrlPrefixes.Add("https://*:30010/BasePathOfAPI/");
            }
            else
            {
                options.UrlPrefixes.Add("http://localhost:5000/BasePathOfAPI/");
            }
        })
        .ConfigureLogging(b =>
        {
            b.AddApplicationInsights("id here");
        })
        .UseNLog()
        .Build();

    return builder;
}

So the setup is almost similar apart from the UrlPrefixes. 因此除了UrlPrefixes之外,设置几乎相似。 The fact that I can both through a gateway and on the windows server call https://somehost/BasePathOfAPI/ and get the message We're running! 事实上,我可以通过网关和Windows服务器调用https://somehost/BasePathOfAPI/并获取消息We're running! displayed in the browser tells me that the API is up and running but it's simply not able to hit any of the controllers if I try. 显示在浏览器中告诉我API已启动并运行,但如果我尝试,它根本无法点击任何控制器。 One example of a controller: 控制器的一个例子:

[Route("api/{someNumber:int}/Home")]
[ApiController]
public class HomeController: ControllerBase
{
    //ctor and props ommitted

    [HttpGet("GetSomeData")
    [ProducesResponseType(StatusCodes.200OK)]
    public async Task<IActionResult> GetSomeData()
    {
        //implemenetation
    }
}

Now, the url I'm using to try and get to the above controller is: 现在,我用来尝试访问上述控制器的URL是:

https://somehost/BasePathOfAPI/api/1234/Home/GetSomeData

Which returns in a 404 message: not found, however if I locally run: 在404消息中返回:未找到,但是如果我在本地运行:

http://localhost:5000/BasePathOfAPI/api/1234/Home/GetSomeData

It works fine. 它工作正常。

Not sure where I'm going wrong, maybe something with the UrlPrefixes but should I then be able to get to the middleware if that's incorrect? 不知道我哪里出错了,也许是UrlPrefixes东西,但如果那不正确,我应该能够找到中间件吗? Maybe something with the routing, but then why does it work locally? 也许与路由有关,但为什么它在本地工作?

Solved - The full path base must be added to the UrlPrefix and the urlacl registration so 已解决 - 必须将完整路径库添加到UrlPrefix和urlacl注册中

netsh http add urlacl url=https://*:30010/BasePathOfAPI/ user="NT AUTHORITY\NETWORK SERVICE" 

and in addition to this as controllers are in another dll, the assembly must be referenced in the ConfigureServices method: 除此之外,控制器在另一个DLL中,必须在ConfigureServices方法中引用该程序集:

services.AddMvc().AddApplicationPart(typeof(SystemController).Assembly)

These two fixes made it work 这两个修复使它工作

This may be an issue with the weak wildcard in the UrlPrefix. 这可能是UrlPrefix中弱通配符的问题。

Try this for the production binding instead:- 请尝试使用生产绑定: -

options.UrlPrefixes.Add("https://somehost:30010/BasePathOfAPI/");

Where somehost is the FQDN of the machine. somehost是机器的FQDN。

暂无
暂无

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

相关问题 仅在 UAT web 服务器中部署时出现路由错误 404。 在当地工作。 ASP.NET核心 - Routing error 404 only when deployed in UAT web server. Works locally. ASP.NET Core 引用COM对象的ASP.Net Core 2.0在本地工作,但在部署时无法工作 - ASP.Net Core 2.0 referencing COM objects works locally but not when deployed Angular 8 - 路由在本地工作,但在生产环境中部署时,路由不起作用 - .NET 核心 C# 后端 - Angular 8 - routing works locally, but when deployed on Production, routes don't work - .NET Core C# backend 使用带有更改的侦听器路径的httpsys时,未为ASP.Net Core Service Fabric服务使用NSwag生成的招摇 - Swagger generated using NSwag not found for ASP.Net Core Service Fabric service when using httpsys with altered listener path ASP.Net Core Web API 适用于 IIS Express,但在部署到 IIS 时不起作用 - ASP.Net Core Web API works on IIS Express, but not working when deployed to IIS ASP.NET 核心 gRPC 在本地工作但不在 Docker - ASP.NET Core gRPC works locally but not in Docker ASP.NET核心集成测试在本地工作,但在生产环境中运行时会抛出空引用异常 - ASP.NET Core Integration Test works locally but throws null reference exception when running in production environment ASP.NET Core 2.0 HttpSys Windows 身份验证因 Authorize 属性而失败(InvalidOperationException:未指定身份验证方案) - ASP.NET Core 2.0 HttpSys Windows Authentication fails with Authorize attribute (InvalidOperationException: No authenticationScheme was specified) ASP.NET MVC5 Google API GoogleWebAuthorizationBroker.AuthorizeAsync在本地工作,但未部署到IIS - ASP.NET MVC5 Google APIs GoogleWebAuthorizationBroker.AuthorizeAsync works locally but not deployed to IIS ASP.Net 页面在本地工作但在推送到服务器时失败 - ASP.Net Page Works Locally But Fails When Pushed To Server
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM