简体   繁体   中英

How I can get route (Url) from method via reflection

How I can get route (Url) from method via reflection. From controller and method, like this:

[ApiController]
[Authorize]
[Route("api/events/[controller]")]
public class ApprovedWorksController : ControllerBase
{
    ...
    
    [HttpPost]
    public async Task<IEnumerable<ApprovedWorkResponse>> GetAsync(ApprovedWorkFilter filter)
    {
        ...
    }
}

To:

api/events/ApprovedWorks ...

I use this, for solve problem:

var routeAttribute = controller.GetCustomAttribute(typeof(RouteAttribute));
      if (routeAttribute != null)
            Console.WriteLine(((RouteAttribute) routeAttribute).Template.Replace("/[controller]", "")
                                 + "/" + controller.Name.Replace("Controller", "")
                                 + "/" + methodInfo.Name);

You don't need to use Reflection. All info you need about the HTTP Request can be found in Request and here is screenshot for you to see it in action:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM