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

标签 c# asp.net-core asp.net-mvc-routing

出于某种原因,当我在 Windows 服务器上使用 HttpSys 运行我的 ASP.NET Core API(通过服务结构)时,路由不起作用,而本地一切正常。问题是中间件工作正常,所以我知道请求正在处理,但它永远无法命中任何 Controller ,它只是默认为我的 app.run("Some 404 response") 404中间件。我的一些代码:

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\" }");
        });
    }
}

程序.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;
}

因此除了 UrlPrefixes 之外,设置几乎相似。事实上,我可以通过网关和 Windows 服务器调用 https://somehost/BasePathOfAPI/ 并在浏览器中显示消息 We're running!告诉我 API 已启动并正在运行,但如果我尝试,它根本无法访问任何 Controller 。 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
    }
}

现在,我用来尝试访问上述 Controller 的 url 是:

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

返回 404 消息:未找到,但是如果我在本地运行:

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

它工作正常。

不确定我哪里出错了,也许是 UrlPrefixes 的问题,但如果那不正确,我是否应该能够访问中间件? 也许与路由有关,但为什么它在本地工作?

最佳答案

已解决 - 必须将完整路径基添加到 UrlPrefix 和 urlacl 注册中

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

除此之外,由于 Controller 位于另一个 dll 中,因此必须在 ConfigureServices 方法中引用程序集:

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

这两个修复使其工作

关于c# - ASP.NET Core (HttpSys) 路由在本地工作,但在部署时不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57402949/

相关文章:

razor - Asp.net Core 如何渲染 View

c# - 从 Controller 获取 JsonOptions

c# - 有什么方法可以在 SHFB 中导入外部项目或主题文件?

python - 使用 TCP/socket 将字符串列表从 Python 发送到 C#

c# - 为 Epplus Excel 文件创建最小起订量

asp.net-mvc - 允许在 asp.net mvc 2 Controller 名称的 URL 中使用连字符

asp.net-mvc - url中没有 Controller 的MVC路由

c# - 如何始终显示下划线字符? (C# Windows 窗体)

c# - DateTime.ToString ("MM/dd/yyyy HH:mm:ss.fff") 导致类似于 "09/14/2013 07.20.31.371"

asp.net-mvc-3 - ASP.NET MVC C# 路由 - 传递空整数