标签: kestrel-http-server

记录每个请求的客户端 IP - kestrel 的访问日志

有没有办法用 Kestrel 托管来记录客户端 ip?我在应用程序设置中指定了 DEBUG 日志级别,但它仍然只显示正在请求的服务器路径,而不显示来自谁。

我知道客户端 IP 可以从每个 api 内的结构中获取HttpContext,但我想要的只是通过框架记录它,这样我就可以节省在每个 api 中添加相同的函数。

dbug: Microsoft.AspNetCore.Server.Kestrel[1]
      Connection id "0HL9L7IJ7JLIV" started.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://192.168.1.110:2180/   <====== it logs the server path
dbug: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[9]
      AuthenticationScheme: Bearer was not authenticated.
dbug: Microsoft.AspNetCore.Routing.RouteBase[1]
      Request successfully matched the route with name 'default' and template '{controller}/{action}'.
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action CH.Api.Controllers.HomeController.Index (CH)
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Executing action method CH.Controllers.HomeController.Index (CH) with arguments ((null)) - ModelState is Valid
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      ...
dbug: Microsoft.AspNetCore.Server.Kestrel[9]
      Connection …
Run Code Online (Sandbox Code Playgroud)

asp.net kestrel-http-server asp.net-core

3
推荐指数
1
解决办法
4576
查看次数

https 使用手动 ssl 证书和 kestrel useHttps

我正在尝试使用 https 和 .Net Web API 设置一个简单的 API。

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseKestrel(options =>
            {
                string key = {{private.key}} //is this the password it wants?
                options.Listen(IPAddress.Any, 50790);
                options.Listen(IPAddress.Any, 40354, listenOptions =>
                {
                    listenOptions.UseHttps("certificate.crt", key);
                });
            })
            .Build();

}

//{{private.key}} is the private key in a string.
Run Code Online (Sandbox Code Playgroud)

在启动和连接 http 时使用它可以正常工作,但是一旦我尝试使用 https,我就会收到巨大的错误并且没有响应发送到客户端。

从让我们加密得到一个证书:ca_bundle.crt、certificate.crt 和 private.key。

这是我尝试使用 https 连接时遇到的错误:

失败:Microsoft.AspNetCore.Server.Kestrel[0] 从 IConnectionAdapter 的 OnConnectionAsync 方法未捕获异常。System.NotSupportedException:服务器模式 SSL 必须使用具有关联私钥的证书。在 …

c# ssl asp.net-web-api kestrel-http-server

3
推荐指数
1
解决办法
4436
查看次数

带有 Apache 和反向代理的 Linux ASP.Net core

我需要澄清 ASP.NET Core 应用程序在 Linux 上的设置过程。我有 Apache 作为服务器,我想用它作为反向代理。在我的 ASP.NET Core 应用程序上,我有这样的设置:

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders =
        ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
Run Code Online (Sandbox Code Playgroud)
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
Run Code Online (Sandbox Code Playgroud)

转发标头 - 这些位于“如何在 Linux 上运行 ASP.NET Core”的文档中。

在 Program.cs 中我有:

var host = WebHost.CreateDefaultBuilder(args)
    .UseKestrel()
    .UseUrls("https://*:5001")
    .UseIISIntegration()
    .UseStartup<Startup>()
    .Build();
Run Code Online (Sandbox Code Playgroud)

我有的问题:

  1. 我是否需要这些转发标头?
  2. 我需要添加app.UseHttpsRedirection();到我的项目中吗?
  3. 我需要UseUrls("https://*:5001")在这一行中指定 https 还是可以是 http ?
  4. 我的 Kestrel(我的应用程序)上是否需要使用 https,或者如果我有反向代理,我可以使用 http 并且 Apache 将处理 ssl?
  5. 我的 ASP.NET Core 应用程序中是否需要有任何其他代码才能使其与反向代理一起使用?

c# apache kestrel-http-server asp.net-core

3
推荐指数
1
解决办法
1592
查看次数

SignalR Core Apache WS 意外响应代码:200

我目前正在 Ubuntu Apache Web 服务器上使用 SignalR 运行 .Net Core 应用程序。此 .Net Core 应用程序可通过 example.com/api 路径访问。

我还在网络服务器上运行了一个 Vue JS 应用程序。当我尝试建立与 SignalR 应用程序的 websocket 连接时,出现以下错误:

与“wss://example.com/api/mainHub?id=V3XZrhdsQDTTMIZvQ-8cbQ”的 WebSocket 连接失败:WebSocket 握手期间出错:意外响应代码:200

错误:无法启动传输“WebSockets”:null

.Net Core 应用程序的 Apache 配置如下:

#Main/Desired Path - https://example.com
<VirtualHost *:443>
        DocumentRoot /var/www/example.com/dist/spa
        ServerName example.com

#SSL Certs
        SSLEngine on
        SSLProtocol all -SSLv2
        SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:!RC4+RSA:+HIGH:+MEDIUM:!LOW:!RC4
        SSLCertificateFile /etc/apache2/ssl/example.crt
        SSLCertificateKeyFile /etc/apache2/ssl/server.key
        SSLCertificateChainFile /etc/apache2/ssl/example.ca-bundle

#Upgrade Websockets
        RewriteEngine on
        RewriteCond %{HTTP:UPGRADE} ^WebSocket$ [NC]
        RewriteCond %{HTTP:CONNECTION} Upgrade$ [NC]
        RewriteRule /(.*) ws://localhost:5000/$1 [P]

#Other specific directories
        ProxyPreserveHost On
        ProxyPass …
Run Code Online (Sandbox Code Playgroud)

apache2 signalr kestrel kestrel-http-server asp.net-core-signalr

3
推荐指数
1
解决办法
2113
查看次数

ASP.NET Core / Kestrel 无法一致地提供静态内容

背景信息:

  • ASP.NET Core v3.1 带 RazorPages
  • 在本地运行良好(本地主机上的 Win10 和 Kestrel)
  • 在部署到 Linux VM (Ubuntu 18) 时, wwwroot/ 中的文件返回 404 ,Bootstrap 在本地工作正常,没有 404
  • 发布方式dotnet publish -r linux-x64
  • 部署的应用程序正在运行 Kestrel 并转发来自 NGINX 的请求。

启动.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    /// Included before other middleware (needed due to nginx forwarding)
    /// Per: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/linux-nginx?view=aspnetcore-3.1
    app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseCookiePolicy(); // -- Added …
Run Code Online (Sandbox Code Playgroud)

http-status-code-404 razor twitter-bootstrap kestrel-http-server asp.net-core

3
推荐指数
1
解决办法
1513
查看次数

kestrel-dotnetapp.service:在步骤 EXEC 生成 /usr/local/dotnet 时失败:权限被拒绝

我正在尝试使用 MS Enter中给出的步骤在 Centos8 中安装 .NET Core(3.1) 应用程序。

根据 Microsoft 文档的服务文件/etc/systemd/system/kestrel-dotnetapp.service

[Unit]  
Description= .NET Web API App for centos

[Service]
WorkingDirectory=/var/Application/netcoreapp31
ExecStart=/usr/local/dotnet /var/Application/netcoreapp31/helloapp.dll
Restart=always
# Restart service after 10 seconds if the dotnet service crashes:  
RestartSec=10
KillSignal=SIGINT
SyslogIdentifier=dotnetapp
User=user
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

当我这样做时>sudo systemctl start kestrel-dotnetapp.service出现错误。

Jun 04 22:51:28 主机名 systemd[1827]: kestrel-dotnetapp.service: 无法执行命令:权限被拒绝
Jun 04 22:51:28 主机名 systemd[1827]: kestrel-dotnetapp.service: 在步骤 EXEC 生成时失败/usr/local/dotnet:权限被拒绝
-- 主题:进程 /usr/local/dotnet 无法执行
-- 定义者:systemd

找到下面的ls -la

[user@hostname dotnet]$ ls …
Run Code Online (Sandbox Code Playgroud)

linux centos .net-core kestrel-http-server asp.net-core

3
推荐指数
1
解决办法
9806
查看次数

添加新包会破坏 .NET 5 应用程序

我一直试图找出为什么我的控制台应用程序在引入新包后立即失败。使用IdentityModel.OidcClientand有效,但添加时会引发异常。我也不在代码中引用新包,我只是将其添加到项目中。Microsoft.AspNetCore.Server.Kestrel Microsoft.Extensions.Configuration.Json

重现步骤:

  1. 克隆https://github.com/IdentityModel/IdentityModel.OidcClient.Samples.git

  2. 将NetCoreConsoleClient升级到 .NET 5(更新包)。

  3. 删除Serilog.Sinks.Literate过时的包。

  4. 在 Program.cs 中删除对 SeriLog 的调用.WriteTo.LiterateConsole并添加using IdentityModel.Client.

  5. 为类中的方法添加CancellationToken cancellationToken = new CancellationToken()参数。接口的签名已更改,新方法应如下所示:InvokeAsyncSystemBrowserIBrowserpublic async Task<BrowserResult> InvokeAsync(BrowserOptions options, CancellationToken cancellationToken = new CancellationToken())

  6. 运行应用程序并使用 alice/alice 登录。获取token成功。

  7. 添加包Microsoft.Extensions.Configuration.Json

  8. 运行应用程序。Object reference not set to an instance of an object现在写入 http 响应时会引发异常。

LoopbackHttpListener.SetResult写入响应时发生异常:ctx.Response.WriteAsync("<h1>You can now return to the application.</h1>");

为什么添加一个包会对运行时产生如此大的影响?

项目文件: …

c# kestrel-http-server identitymodel .net-5

3
推荐指数
1
解决办法
1090
查看次数

ASP.NET Core 通过 HTTP 接收自定义配置来配置 Kestrel

这感觉像是一个需要解决的简单问题,但在我的所有搜索中,我仍然没有找到适合我的解决方案。可能是另一种找不到我想要的东西的情况,因为我没有寻找正确的“东西”,但我们在这里......

我有一个 C# Web API 程序,我想从配置对象配置 kestrel 服务器。

我通过休息调用将此配置接收到我的服务中,进入一个CustomConfig对象。我可以在 inProgram.cs或 in 中获取此配置对象Startup.cs,但由于我不想重复自己并进行额外的调用,所以我不想在这两个地方都这样做。

我的偏好是获取配置,Startup.cs因为这是我的其余配置代码所在的位置,并且是我已经使用我的CustomConfig对象的位置。但是,我找不到一种方法来配置 kestrel 服务器以使用我提供给它的证书(在 Startup.cs 中),也找不到一种将此配置注入到Startup.csfrom的方法Program.cs

在其他项目中,我已将 PFX 文件的位置作为环境变量传递:(ASPNETCORE_Kestrel__Certificates__Default__Path在这种情况下,一切都可以正常工作,无需额外的代码配置),但在这个项目中,所有配置都必须通过其余调用检索,因此这里不是一个选项。

我目前一切都在运行,但只能通过两次其余调用来获取配置。配置 kestrel 的当前实现是将 PFX 存储CustomConfig为 base64 字符串,并在以下位置进行配置Program.cs

public static IHostBuilder CreateHostBuilder(string[] args)
        {
            return Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    CustomConfig config = CustomConfig() // <- I receive config here
                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseKestrel(options =>
                    {
                       options.ConfigureHttpsDefaults(d =>
                       {
                           byte[] pfxBytes = Convert.FromBase64String(config.Base64PFXBytes);
                           d.ServerCertificate …
Run Code Online (Sandbox Code Playgroud)

c# kestrel-http-server asp.net-core asp.net-core-webapi

3
推荐指数
1
解决办法
1196
查看次数

从 C# 6 中的响应标头中删除 SERVER

我有一个 .net 6.0 C# API(使用 Kestrel 服务器在 Mac 上开发),它在响应标头中返回服务器。我尝试过的所有解决方案均适用于 6 年级之前的学生,并且不再相关。

我在我的Program.cs中尝试过:

app.Use((ctx, next) => {
    var headers = ctx.Response.Headers;

    headers.Add("X-Frame-Options", "DENY");
    headers.Add("X-XSS-Protection", "1; mode=block");
    headers.Add("X-Content-Type-Options", "nosniff");
    headers.Add("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload");

    headers.Remove("Server");

    return next();
});
Run Code Online (Sandbox Code Playgroud)

这不会删除服务器,但会添加其他标头。如果我添加带有空格的服务器属性(例如headers.Add("Server", "");),则不会显示服务器名称 (Kestrel),但标头属性仍然会出现。这可能达到了目的,但我宁愿它根本不出现。

ChatGPT(我知道,但我尝试了它作为最后的手段),建议

var host = new WebHostBuilder().UseKestrel(options => options.AddServerHeader = false).UseStartup<StartupBase>().Build();
Run Code Online (Sandbox Code Playgroud)

但这给出了运行时错误无法实例化服务类型“Microsoft.AspNetCore.Hosting.IStartup”的实现类型“Microsoft.AspNetCore.Hosting.StartupBase”。

作为一个不太重要的附带问题,由于删除服务器是最佳实践,我想知道为什么默认功能是包含它而不是省略它。难道不应该有责任添加它吗?包含该值的用例是什么?

c# response-headers kestrel-http-server .net-6.0

3
推荐指数
1
解决办法
5402
查看次数

在不使用Microsoft.AspNetCore.TestHost中包含的TestServer的情况下运行Kestrel进行测试

我正在使用SoapCore使用asp.net core 2创建WCF类的应用程序。

这样做对我来说很好,但是在集成测试端点时遇到了一些障碍。

由于SoapCore是中间件,并且与任何api控制器都没有关系,因此我无法使用HttpClient来测试端点,因此TestServer对我没有用。

我的问题是在不使用TestServer的情况下如何与我的集成测试并行运行kestrel,或者在这种情况下是否可以利用TestServer?

我认为这里的任何代码都没有用,但是到目前为止,我得到的是以下内容。

启动文件

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IPaymentService>(service => new Services.PaymentService());
        services.AddMvc();
    }

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

        app.UseSoapEndpoint<IPaymentService>("/PaymentService.svc", new BasicHttpBinding());
        app.UseMvc();
    }
}
Run Code Online (Sandbox Code Playgroud)

PaymentService

[ServiceContract]
public interface IPaymentService
{
    [OperationContract]
    string ReadPaymentFiles(string caller);
}

 public class PaymentService : IPaymentService
{
    public string ReadPaymentFiles(string caller)
    {
        return caller;
    } …
Run Code Online (Sandbox Code Playgroud)

c# testing kestrel-http-server asp.net-core asp.net-core-2.0

2
推荐指数
1
解决办法
932
查看次数