Created
March 11, 2015 11:05
-
-
Save yngvebn/fd6ecd8b835b0fa62053 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 string Link<TController>(Expression<Func<TController, IHttpActionResult>> method) | |
where TController : ApiController | |
{ | |
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); | |
} | |
public string View<TController>(Expression<Func<TController, System.Web.Mvc.ActionResult>> method) | |
where TController : System.Web.Mvc.Controller | |
{ | |
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<System.Web.Mvc.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