c# - 如何在 ASP.NET Core 中使用 HttpContextAccessor 读取 URI 参数

标签 c# asp.net-core httpcontext route-parameters

我正在尝试使用 IHttpContextAccessor 接口(interface)及其默认实现 HttpContextAccessor 从 DelegatingHandler 中读取发送到 WEB API 操作方法的 URL 参数。

Controller 看起来像这样:

[HttpPost("{siteName}/{accountID}")]
public async Task<ActionResult<AirRequest>> Post(AirCModel model, string siteName, string accountID)
{

}

我想读取 DelegatingHandler 中的值 {siteName}/{accountID}

public class AuthenticationDelegatingHandler : DelegatingHandler
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public AuthenticationDelegatingHandler(IHttpContextAccessor httpContextAccessor)
    {      
        _httpContextAccessor = httpContextAccessor;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var siteNAme = _httpContextAccessor ???
    }
}

在 Startup.cs 中我注入(inject)了 HttpContext 服务:

public void ConfigureServices(IServiceCollection services)
{                   
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddHttpContextAccessor();
}

最佳答案

您可以拉出HttpContext RouteData 调用 GetRouteData 扩展方法,然后从那里读取各个值。这是一个例子:

var routeData = _httpContextAccessor.HttpContext.GetRouteData();
var siteName = routeData.Values["siteName"];
var accountID = routeData.Values["accountID"];

GetRouteData扩展方法位于 Microsoft.AspNetCore.Routing命名空间,因此您可能需要添加 using Microsoft.AspNetCore.Routing;相应地。

关于c# - 如何在 ASP.NET Core 中使用 HttpContextAccessor 读取 URI 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56461701/

相关文章:

c# - 滚动时图像是如何下载的?

c# - 如何通过反射为参数的默认值调用方法

C#:使用 Excel.interop 获取单元格的值

c# - 连接 XML 节点数据

asp.net-core - 部署时未提供 Nuget 包内容文件

c# - Asp.net core 2 CORS预检请求响应缓慢

asp.net-mvc - 使用 ASP.NET MVC 的 TempData 和 Faked HttpContext 问题

c# - 如何在 SeriLog Sink 中获取当前的 HttpContext?

razor - 项目中不存在目标 "ResolveTagHelperRazorGenerateInputs"

c# - NTLM 和 Kerberos 之间的 HttpContext 差异