-
Notifications
You must be signed in to change notification settings - Fork 0
/
RouteInfoController.cs
70 lines (67 loc) · 2.35 KB
/
RouteInfoController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Routing;
using System.Web.Services.Protocols;
namespace Web.Controllers.Api
{
public class RouteInfoController : ApiController
{
[Route("api/route-table"), HttpGet, AllowAnonymous]
public HttpResponseMessage GetRouteInfo()
{
var controllerClasses =
Assembly.GetExecutingAssembly()
.DefinedTypes
.Where(type => typeof(ApiController).IsAssignableFrom(type))
.SelectMany(type =>
type
.DeclaredMethods
.Select(method => new
{
Route = method.GetCustomAttribute<RouteAttribute>()?.Template,
ClassName = type.Name,
MethodName = method.Name,
HttpVerb = GetHttpMethod(method),
Authentication = method.GetCustomAttribute<AllowAnonymousAttribute>() == null,
Role = method.GetCustomAttribute<AuthorizeAttribute>()?.Roles
})
.Where(o => o.Route != null)
)
.OrderBy(t => t.Route)
.ToList();
return Request.CreateResponse(HttpStatusCode.OK, controllerClasses);
}
string GetHttpMethod(MethodInfo method)
{
var httpMethodAttr = method.GetCustomAttributes()
.SingleOrDefault(m => typeof(IActionHttpMethodProvider)
.IsAssignableFrom(m.GetType()));
if (httpMethodAttr == null)
{
return null;
}
else if (httpMethodAttr is HttpGetAttribute)
{
return "GET";
}
else if (httpMethodAttr is HttpPostAttribute)
{
return "POST";
}
else if (httpMethodAttr is HttpPutAttribute)
{
return "PUT";
}
else if (httpMethodAttr is HttpDeleteAttribute)
{
return "DELETE";
}
return null;
}
}
}