Home > database >  ASP.NET Core 3.1, get the controller and action name from referrer url in the current HttpContext
ASP.NET Core 3.1, get the controller and action name from referrer url in the current HttpContext

Time:09-05

I need to get the routedata information, specifically controller and action name for the current reqests referrer url. I am using the endpoint routing feature. I read somewhere IRouter is not applicable if endpoint routing feature is enabled.

//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    
}

Startup.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();
    });
}

Any pointer or idea would be appreciated. Thanks in advance.

CodePudding user response:

I'm not sure where you are writing this code but here's a .NET 6 application that shows how to get access to the endpoint and the ControllerActionDescriptor from a custom middleware:

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

CodePudding user response:

You could check the document related with Routing,and in the doc it has been mentioned:

When a routing middleware executes, it sets an Endpoint and route values to a request feature on the HttpContext from the current request:

Calling HttpContext.GetEndpoint gets the endpoint.

HttpRequest.RouteValues gets the collection of route values.

You could try

HttpContext.Request.RouteValues["controller"].ToString();

and

HttpContext.Request.RouteValues["action"].ToString();

If you have further issue on the case,please show us more details

  • Related