0

I use Web Api for list of tales and I want to do this:

  1. List GetAllTales() = api/tales/
  2. Tale GetTale(int id) = api/tales/1
  3. List GetAllTalesByCategory(string categoryName) = api/tales/kids
  4. Tale GetTalesByCategoryAndId(string categoryName, int id) = api/tales/kids/1

I dont know what can ı do this or what can I change in route config?

My TalesController:ApiController

public IEnumerable<Tale> GetAllTales()
    {
        return TaleService.FindAllTale();
    }
public IEnumerable<Tale> GetAllTalesByCategory(string categoryName){}

    public Tale GetTale(int id)
    {
        Tale item = TaleService.FindByTaleId(id);
        if (item == null)
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        }

        return item;
    }

Its my WebApiConfig

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

Some example for my aim : http://www.bbc.com/news/ - http://www.bbc.co.uk/news/technology/

BerdaN
  • 49
  • 1
  • 9

2 Answers2

0

use the [HttpPost] and [HttpGet] attributes and specify the action name with [ActionName("Your Action Name")]

// api/tales/getall
[HttpGet]
[ActionName("getall")]
public IEnumerable<Tale> GetAllTales()
{
    return TaleService.FindAllTale();
}

like this you can decorate all the action with proper attributes to get it working as expected.

Edit

You can refer this answer for creating multiple routes Routing in Asp.net Mvc 4 and Web Api

Community
  • 1
  • 1
Anto Subash
  • 3,140
  • 2
  • 22
  • 30
  • Thanks for answer. I got it and I change my code but if ı write "/api/tales/kids" this request use GetTale(int id). And I didnt use [ActionName] with GetAllTalesByCategory function. Because this function have a lot of thing(entertainment...). I think I have to write diffirent MapRoute. – BerdaN Dec 11 '13 at 16:05
  • see my edit it has an SO question which help you to create multiple routes. – Anto Subash Dec 13 '13 at 08:52
  • I see and try something like that but again I didnt do it. So I change a little my question. Now it's more understandable. – BerdaN Dec 13 '13 at 15:32
0
config.Routes.MapHttpRoute(
        name: "DefaultApiAction", 
        routeTemplate: "api/{action}/{name}/{controller}/{resourceId}",
        defaults: new { resourceId= RouteParameter.Optional }
        constraints: new { name = @"^[a-z]+$" }
    );

maybe you can try define this route ,and add ActionName like Anto's answer .