Keith Pinson
Keith Pinson

Reputation: 7985

Library function to generate URL from an ASP.Net Web API controller?

While writing some acceptance test code against a ASP.Net Web API controller, I hardcoded the URL (minus the domain and port) to be posted against. This makes me uneasy; if the controller or one of its parameters were renamed, my URL would become invalid, but Intellisense/Resharper would not catch it. Is there a method that will generate the appropriate URI for a controller?

Example: given a controller that looks something like this:

public class FooController : ApiController
{
    ...
    public HttpResponseMessage Get(string bar) { ... }
    public HttpResponseMessage Post(string bar) { ... }
    ...
}

Say I write some test code that looks something like this (conceptual):

sendPOSTforJSONresponse(baseURL + "api/Foo?bar=" + bar);
...
sendGETforJSONresponse(baseURL + "api/Foo?bar=" + bar);

but what I want to do is replace "api/Foo?bar=" with something like GenerateURLForController(FooController).withParametersOfMethod(FooController.Get). Is there a method like this in the standard ASP.Net Web API libraries? If not, I suppose I can roll my own using reflection.

Upvotes: 1

Views: 270

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

There is a project that does this: Hyperlinkr.

Syntax is like this:

var uri = linker.GetUri<FooController>(r => r.Get(<parameter values go here>));

Upvotes: 2

Related Questions