user2859298
user2859298

Reputation: 1443

Web API 2 - restful service - URL encoded

I have created a RESTful service using web API 2. I have the following route to return information about a stock item :

http://localhost/api/stockitems/{stockCode}

i.e. http://localhost/api/stockitems/BOMTEST1

I have stock codes in my system that contain forward slashes i.e. CA/BASE/SNG/BEECH. Naturally i can't request the details using the standard convention due to the slashes.

http://localhost/api/stockitems/CA/BASE/SNG/BEECH

I have tried URL encoding but it's not hitting the controller

http://localhost/api/stockitems/CA%2FBASE%2FSNG%2FBEECH

I just keep getting a 404

How do i handle this in Web API?

Upvotes: 2

Views: 995

Answers (1)

DoctorMick
DoctorMick

Reputation: 6793

You will need to change your WebApiConfig. If you don't use IDs in more than this place you can just add a wildcard ({*id}) in to that part of the config:

config.Routes.MapHttpRoute(
    name: "Default",
    routeTemplate: "api/{controller}/{*id}",
    defaults: new { id = RouteParameter.Optional }
);

I'd recommend creating a specific route for this case tho (assuming it is the only scenario where you need to allow slashes):

config.Routes.MapHttpRoute(
    name: "StockItems",
    routeTemplate: "api/stockitems/{*id}",
    defaults: new { controller = "StockItems", id = RouteParameter.Optional }
);

You won't need to url encode the URLs this way.

Upvotes: 3

Related Questions