Created
March 11, 2015 08:50
-
-
Save yngvebn/10704659332cc1d4394b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BaseController: ApiController | |
{ | |
public string Link<TController>(Expression<Func<TController, IHttpActionResult>> method) | |
where TController : ApiController | |
{ | |
UrlHelper url = new UrlHelper(this.Request); | |
var methodCallExpression = (method.Body as MethodCallExpression); | |
if (methodCallExpression == null) throw new Exception("Not a method"); | |
var action = methodCallExpression.Method; | |
var arguments = methodCallExpression.Arguments; | |
var methodParameters = action.GetParameters(); | |
var routeAttribute = action.GetCustomAttribute<RouteAttribute>(); | |
if (routeAttribute == null || string.IsNullOrEmpty(routeAttribute.Name)) | |
{ | |
throw new Exception("Missing RouteAttribute with Name"); | |
} | |
var parameters = new Dictionary<string, object>(); | |
for (int i = 0; i < methodParameters.Length; i++) | |
{ | |
LambdaExpression lambda = Expression.Lambda(arguments[i]); | |
var val = lambda.Compile().DynamicInvoke(); | |
parameters.Add(methodParameters[i].Name, val); | |
} | |
return url.Link(routeAttribute.Name, parameters); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment