Mathias Lundin
Mathias Lundin

Reputation: 11

Pass URL containing a query string as a parameter ASP.Net Web API GET?

I'm trying to pass in an URL as a string parameter to a WEB API GET method.

The controller:

public class LinksController : ApiController
{
    public HttpResponseMessage Get(string targetUrl)
    {
        //query db with targetURL
    }
}

The aim is to query the database to see if the URL is stored. This works fine with simple URLs and URLs whose query string contains a single parameter, like:

The problem I'm encountering is specifically when the query string contains multiple parameters, e.g.

When debugging, the value of targetUrl is only ".../watch?v=nLPE4vhSBx4" which means &feature=youtube_gdata is lost.

The GET request looks like this:

http://localhost:58056/api/links?targetUrl=http://www.youtube.com/watch? v=nLPE4vhSBx4&feature=youtube_gdata

I've also tried to add the following route in WebApiConfig.cs:

config.Routes.MapHttpRoute(
    name: "Links",
    routeTemplate: "api/links/{targetUrl}",
    defaults: new { controller = "Links", targetUrl= RouteParameter.Optional }
);

But the GET request then results in 400 Bad Request.

So my question is, can't this be done? I would like the complete URL! Or would I need to change the method header to use the [FromBody] attribute and pass it as a JSON object?

Upvotes: 1

Views: 2811

Answers (1)

Jon Limjap
Jon Limjap

Reputation: 95432

You should URLEncode your target URL parameter so that it doesn't get mistaken for subsequent query string parameter. This means the URL you specified should appear as:

http://localhost:58056/api/links?targetUrl=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DnLPE4vhSBx4%26feature%3Dyoutube_gdata

And then inside your Get method, URLDecode the string that is passed as a parameter.

Both methods can be found in System.Web.HttpUtility

Upvotes: 1

Related Questions