Skip to content

Instantly share code, notes, and snippets.

@ChrisMissal
Last active December 29, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChrisMissal/7667508 to your computer and use it in GitHub Desktop.
Save ChrisMissal/7667508 to your computer and use it in GitHub Desktop.
URLs as JSON to be used on the client
<script>
define('urls', [], function () {
return @{ Html.RenderAction("GetApiUrls", "Api");};
});
</script>
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();
}
}
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