voutrin
voutrin

Reputation: 21

Multiple PUT actions, asp.net mvc 4 web api

I'm trying to build an web api using asp.net mvc 4 for this. Let suppose that we have Books resource. Get, Post, Delete works fine but in case Post I'm a little confused. The way how I want to use PUT is CQRS like: one action PUT for updating Title, another action PUT to update Authors and an other one to make the book favorite. All this PUT actions are overloaded with different types of commands and they have just one parameter. When I try to make a a PUT request to this resource routing from MVC fails, saying that are multiple PUT action that match the request. Could anybody suggest how to configure routing to handle:

public HttpResponseMessage Put(MakeFavorite mf){/*code*/}

public HttpResponseMessage Put(ChangeTitle ct){/*code*/}

public HttpResponseMessage Put(UpdateAuthor ua){/*code*/}

Upvotes: 2

Views: 3664

Answers (2)

David East
David East

Reputation: 32604

Since each function doesn't really have much to do with one another, you should try putting each put method in separate respective controllers.

public class MakeFavoriteController : ApiController
{
    public HttpResponseMessage Put(MakeFavorite mf)
    {
        // Code
    }
}

public class ChangeTitleController : ApiController
{
    public HttpResponseMessage Put(ChangeTitle ct)
    {
        // Code
    }
}

public class UpdateAuthorController : ApiController
{
    public HttpResponseMessage Put(UpdateAuthor ua)
    {
        // Code
    }
}

Upvotes: 0

Aleksei Anufriev
Aleksei Anufriev

Reputation: 3236

I think it is better not to apply RPC here, even David solution has some RPC artifacts. First of all you should design youe URI structure. For example:

/books/{bookId}/favouritestate/{state}  
/books/{bookId}/title/{title}  
/books/{bookId}/author/{author}  

Then update your routing table to handle this:

   routes.MapHttpRoute(
                name: "BookTitleApiRoute",
                routeTemplate: "books/{bookId}/title/{title}  ",
                defaults: new {controller = "BookTitleController", title = RouteParameter.Optional}
                );

Then add some controllers. For example:

 public class BookTitleController : ApiController
    {
        // GET /books/{bookId}/title/
        public HttpResponseMessage Get(string bookId)
        {
            return your book title
        }
        // PUT /books/{bookId}/title/{title}
        public HttpResponseMessage Put(string bookId,string title)
        {
            update book title and return result
        }

    }

You also can interpet relations between objects like that and etc.

Hope this will help ypu to build nice RESTful API =))

Upvotes: 6

Related Questions