c# - ASP.NET Core 3.1,从当前HttpContext中的referrer url获取 Controller 和操作名称

标签 c# asp.net-core

我需要获取路由数据信息,特别是当前请求引荐网址的 Controller 和操作名称。 我正在使用端点路由功能。我在某处读到,如果启用端点路由功能,则 IRouter 不适用。

//var router = context.HttpContext.RequestServices.GetService<IRouter>();
//router is null, since i used UseEndpoints routing i guess
Uri urlReferrer = context.HttpContext.Request.GetTypedHeaders().Referer;
if (urlReferrer != null)
{
    var requestFeature = new HttpRequestFeature()
    {
        Method = "GET",
        PathBase = string.Empty,
        Path = urlReferrer.AbsoluteUri,
        QueryString = urlReferrer.Query
    };
    var features = new FeatureCollection();
    features.Set<IHttpRequestFeature>(requestFeature);
    var httpContext = new DefaultHttpContext(features);
    var ep = httpContext.GetEndpoint();
    //ep is null since the context is not passed through routing, i guess
    //how do i pass this httpcontext though routing middleware to get the route values

    //tried RouteAsync but IRouter is null
    //var routeContext = new RouteContext(httpContext);
    //context.RouteData.Routers.Add(router);
    //await router.RouteAsync(routeContext);

    var reffererActionName = httpContext.GetRouteData().Values["action"].ToString();
    var reffererControllerName = httpContext.GetRouteData().Values["controller"].ToString();
    //i need the action+controller name for the referrer url    
}

启动.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider sp)
{
    ...

    app.UseRouting();

    ...

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Landing}/{action=Index}/{id?}");

        //endpoints.MapRazorPages();
    });
}

任何指针或想法将不胜感激。提前致谢。

最佳答案

我不确定您在哪里编写此代码,但这里有一个 .NET 6 应用程序,它演示了如何从自定义中间件访问端点和 ControllerActionDescriptor:

using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();

app.Use((context, next) =>
{
    var controllerActionDescriptor = context.GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>();

    if (controllerActionDescriptor != null)
    {
        // Get the controller information here
    }

    return next(context);
});

app.MapControllers();

app.Run();

public class MyController : ControllerBase
{
    [HttpGet("/")]
    public string Get() => "Hello World";
}

关于c# - ASP.NET Core 3.1,从当前HttpContext中的referrer url获取 Controller 和操作名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73597158/

相关文章:

c# - C#中 "if(object is type)"的速度

c# - System.Diagnostics.Tracing.EventSource.IsEnabled 是如何工作的?

c# - 在带有用户控件的主窗口中使用 RoutedCommand

c# - 使用 NHibernate 加密和解密数据

centos - 如何在 CentOs 机器上安装 .net 核心?

c# - 从 PropertyGrid 显示详细的文件夹浏览器

angular - 使用 SIGNAL R 的 angular 7 和 ASP.NET core 2.2 的 CORS 策略问题

c# - 如何将字符串传递给 Angular 中的发布请求?

c# - 如何修复 .net core 2.2 应用程序中找不到的 swagger.json

c# - 在 ASP.NET 2.0 上移动或删除了 IdentityRole 中的用户属性