0

I am using an ASP Webapi2 .net project

I am trying to write a controller that takes in a latitude, longitude and a timespan as parameters - which then returns some JSON data. (a bit like a store locator)

I have the following controller code

public dynamic Get(decimal lat, decimal lon)
        {
            return new string[] { lat.ToString(), lon.ToString()};

        }

and I have put the following line at the top of my WebAPIConfig.cs class

config.Routes.MapHttpRoute(
                name: "locationfinder",
                routeTemplate: "api/{controller}/{lat:decimal}/{lon:decimal}"
            );

When I do the following call I get a 404 error.

http://localhost:51590/api/MassTimes/0.11/0.22

Can I use decimals in the query string? how do i get around this?

GMan
  • 444
  • 1
  • 11
  • 24

2 Answers2

1

Have you considered looking into Attribute Routing, by chance? The URL covers the details, but, when it comes to building APIs in particular, attribute routing really simplifies things and allows patterns to be easily developed into your routes.

If you do end up going this route (ha), you can then do something like this:

[RoutePrefix("api/masstimes")]
public class MassTimesController : ApiController
{
    [HttpGet]
    [Route("{lat}/{lon}")]
    public ICollection<string> SomeMethod(double lat, double lon, [FromUri] TimeSpan time)
    {
        string[] mylist = { lat.ToString(), lon.ToString(), time.ToString() };
        return new List<string>(myList);
    }
}

And you would now get there by calling GET http://www.example.net/api/masstimes/0.00/0.00?time=00:01:10

The article also describes other options available (e.g. [FromBody] and others) which you may find useful.

JasCav
  • 34,458
  • 20
  • 113
  • 170
1

Few things,

First, add a trailing slash to the end of your route. The parameter binding can't determine the end of your decimals unless you force it with a trailing slash.

http://localhost:62732/api/values/4.2/2.5/

Second, take off the type on your route declaration:

config.Routes.MapHttpRoute(
                name: "locationfinder",
                routeTemplate: "api/{controller}/{lat}/{lon}"
            );

Third, don't use decimal. Use double instead, as it is more appropriate for describing latitude and longitude coordinates.

mariocatch
  • 8,305
  • 8
  • 50
  • 71