.Net Web Routing & Help Page

I am trying to get an API help page to show all the API endpoints, and show them in the style I want.

Here are my routes:

config.Routes.MapHttpRoute("Orgs", "v1/Orgs/{orgId}", new { controller = "Orgs", orgId = RouteParameter.Optional }); config.Routes.MapHttpRoute("OrgDescendants", "v1/Orgs/{orgId}/Descendants", new { controller = "Orgs", action = "OrgDescendants" }); 

Here are all my management methods:

 [HttpGet] public IEnumerable<Org> GetAllOrgs() [HttpGet] public Org Get(string orgId) [HttpGet] [ActionName("OrgDescendants")] public List<Org> Descendants(string orgId) [HttpPost] public HttpResponseMessage Post(Org org) [HttpPut] public HttpResponseMessage Put(string orgId, Org org) [HttpDelete] public void Delete(string orgId) 

And here are the endpoints displayed on the help page:

 GET v1/Orgs POST v1/Orgs PUT v1/Orgs/{orgId} DELETE v1/Orgs/{orgId} GET v1/Orgs/{orgId}/Descendants 

As you can see, the following endpoint is missing from the help page:

 GET v1/Orgs/{orgId} 

I tried so many different routing permutations that I lost. No matter what I try, I always end up with the absence of some endpoints or the "wrong" formatting.

For example, I get:

 GET v1/Orgs/{orgId}/Get 

when I want:

 GET v1/Orgs/{orgId} 

or I get:

 PUT v1/Orgs?orgId={orgId} 

when I want:

 PUT v1/Orgs/{orgId} 

No matter what combination I try, I cannot get them the way I want them. Any help would be greatly appreciated!

+6
source share
1 answer

Usually, this problem occurs when there are problems with the project architecture (hierarchy).

Alternatively, you can try adding routers differently. For instance:

 RouteTable.Routes.Add( "UserProfiles", new Route("Profile/{uid}/{mode}", new ProfileRouterHandler("~/Profile/Default.aspx"))); 

The router handler will look something like this:

 public class ProfileRouterHandler: IRouteHandler { private string VirtualPath { get; set; } public ProfileRouterHandler() { } public ProfileRouterHandler(string virtualPath) { VirtualPath = virtualPath; } public IHttpHandler GetHttpHandler(RequestContext requestContext) { string param = requestContext.RouteData.Values["uid"] as string; string mode = requestContext.RouteData.Values["mode"] as string; long id; long.TryParse(param, out id); if (id > 0) { string filePath = "~/Profile/Default.aspx?uid=" + param + (!string.IsNullOrEmpty(mode) ? "&mode=" + mode : ""); VirtualPath = "~/Profile/Default.aspx"; HttpContext.Current.RewritePath(filePath); } else { string filePath = "~/Profile/" + param + ".aspx"; VirtualPath = filePath; HttpContext.Current.RewritePath(filePath); } return BuildManager.CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as Page; } } 

Hope this helps.

0
source

Source: https://habr.com/ru/post/949132/


All Articles