Martijn
Martijn

Reputation: 24789

Why is my Web Api 2 Post method not hit?

In my apicontroller I have 2 methods which can handle Post requests:

public WatchListItemDTO Post(MovieDto movie)
{
    //do smt..
}

[HttpPost]
[Route("MarkMovieAsWatched/{id}")]
public void MarkMovieAsWatched(int id)
{
    // do smt..
}

The controller has prefix attribute: [RoutePrefix("api/DownloadList")]. When I make a (post) request to http://localhost:4229/api/DownloadList/MarkMovieAsWatched/it hits my Post method. The request also contains an object: {id: 12}.

My WebApiConfig:

public static void Register(HttpConfiguration config)
{
    config.EnableCors();

    config.MapHttpAttributeRoutes();

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

    // To disable tracing in your application, please comment out or remove the following line of code
    // For more information, refer to: http://www.asp.net/web-api
    config.EnableSystemDiagnosticsTracing();
}

Could someone explaint to me why the method MarkMovieAsWatched is not hit? And how to solve this?

Upvotes: 0

Views: 1780

Answers (1)

darth_phoenixx
darth_phoenixx

Reputation: 952

It might be that your route requires an id as part of the route.

Try changing your attribute to:

[Route("MarkMovieAsWatched/{id?}")]

That way if you don't pass the id as part of the path, the route will still be a valid match.

Upvotes: 1

Related Questions