Last active
December 29, 2015 11:59
-
-
Save ChrisMissal/7667508 to your computer and use it in GitHub Desktop.
URLs as JSON to be used on the client
This file contains hidden or 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
<script> | |
define('urls', [], function () { | |
return @{ Html.RenderAction("GetApiUrls", "Api");}; | |
}); | |
</script> |
This file contains hidden or 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
using System.Linq; | |
using System.Web.Mvc; | |
using Construction.Core.Features.QuickSearch; | |
using Construction.Core; | |
using Construction.Core.Extensions; | |
using Core.Helpers; | |
using Newtonsoft.Json.Linq; | |
public class ApiController : BaseController | |
{ | |
private static object _clientApiUrls; | |
private object BuildClientApiUrls() | |
{ | |
return new JObject( | |
new JProperty("Root", Url.Content("~")), | |
from url in _clientApiBuilder.GetUrls() | |
select new JProperty(url.Name, | |
new JObject( | |
from method in url.Methods | |
select new JProperty(method.Action, Url.Action(method.Action, method.Controller)) | |
) | |
) | |
); | |
} | |
public string GetApiUrls() | |
{ | |
_clientApiUrls = _clientApiUrls ?? BuildClientApiUrls(); | |
return _clientApiUrls.ToJson(); | |
} | |
} |
This file contains hidden or 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
using System.Collections.Generic; | |
using System.Linq; | |
using System.Web.Mvc; | |
public class ClientApiBuilder | |
{ | |
public IEnumerable<ClientApi> GetUrls() | |
{ | |
return from type in typeof(ApiController).Assembly.GetTypes() | |
where type.IsAssignableTo<Controller>() && !type.IsAbstract | |
let controller = type.Name.Replace("Controller", "") | |
let methods = from method in type.GetMethods() | |
where method.ReturnType.IsAssignableTo<ActionResult>() | |
where !method.HasAttribute<HttpPostAttribute>() | |
select new ClientApiUrl { Action = method.Name, Controller = controller } | |
select new ClientApi { Name = controller, Methods = methods }; | |
} | |
public class ClientApi | |
{ | |
public string Name { get; internal set; } | |
public IEnumerable<ClientApiUrl> Methods { get; internal set; } | |
} | |
public class ClientApiUrl | |
{ | |
public string Action { get; internal set; } | |
public string Controller { get; internal set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment