-2

I am writing a middleware in .net core 2.2. I want to get name of Action and Controller name in the middleware.
I can not use ControllerContext because it not available at that time.
Here is solution in core 3.1 Read Controller and Action name in middleware .Net Core

    public async Task Invoke(HttpContext context)
    {
        await LogRequest(context);
        await LogResponse(context);
    }

    private async Task LogResponse(HttpContext context)
    {
          ServiceName = context ...
    }
शेखर
  • 17,412
  • 13
  • 61
  • 117
  • The HTTPContext is HTML tagged text data. You would have to get parse the HTML to get tag names. The tag names may not match the controller name. – jdweng Mar 09 '21 at 15:02
  • what is your purpose? do you really need to ***pre-route*** for the controller & action info? I mean if you place the code ***after*** `await next ..`, you may have a better chance to get such info, especially with a combination with filters. Trying to obtain such info ***before*** reaching the MVC middleware is very hard, a lot of logic put in MVC middleware and you almost need that same logic to get the desired info. For non-attributed routes, it is easier, but for attributed routes it is very complicated. – King King Mar 09 '21 at 18:38
  • @KingKing after searching on internet I came to know that for controller/action related login it is better to use action filters. I had a classic asp.net filters which I have used modifying that take the help of chunk reading and recyclable memory uses. – शेखर Mar 16 '21 at 04:53

1 Answers1

1

As you are using .net core 2.2,you can only get path and get controller name and action name from it:

var RouteData = context.Request.Path.Value.Split("/");
var controllerName=RouteData[1];
var ActionName=RouteData[2];

If you have area,you need to use:

var RouteData = context.Request.Path.Value.Split("/");
    var controllerName=RouteData[2];
    var ActionName=RouteData[3];

After .net core 3.0,you can use HttpRequest.RouteValues:

string actionName = context.Request.RouteValues["action"].ToString();
string controllerName = context.Request.RouteValues["controller"].ToString();
Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • Thanks I know this approach but if the URL is uniform than you can say this. Means if the `Request.Path` is like `stuent/studentinfo/studentname/10` – शेखर Mar 10 '21 at 07:35