简体   繁体   中英

ASP.net Web API 2 custom methods

I've added this method to my web api controller:

    [HttpPost]
    public bool CreateTrening(int routineId)
    {
        try
        {
            var userId = User.Identity.GetUserId();
            TreningService.CheckIfLastTrenigWasCompleted(userId);
            TreningService.CreateTreningForUser(userId, routineId);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

And I've added another route to my WebApiConfig file, so it looks like this now:

       config.MapHttpAttributeRoutes();

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

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

But when I try to call my method:

/EditWorkout/CreateTrening/1

I get this error:

{"Message":"No HTTP resource was found that matches the request URI '/EditWorkout/CreateTrening/1'.","MessageDetail":"No action was found on the controller 'EditWorkout' that matches the request."}

How can I call my method which is in WebApi controller ?

Calling with that URL to a post method will not work because the post expects the values transmitted in the Http Message body. not in the URL so your controller is not finding the method.

Probably the best solution for this is to encode your posted value in the http message you send the controller, and call the URL with /EditWorkout/CreateTrening, this will work as a post.

Here is another SO thread where the question of how to do this was answered, Specific post question answered

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM