调用我的 WebAPI 方法时出现 HTTP 404

HTTP 404 on invoking my WebAPI method

我正在尝试使用 fiddler 调用下面定义的 WebAPI 方法,但出现以下异常。请让我知道我在这里遗漏了什么,因为我无法使用定义的方法。

方法原型:

[Route("api/tournament/{tournamentId}/{matchId}/{teamId}/{userEmail}/PostMatchBet")]
public HttpResponseMessage PostMatchBet(int tournamentId, int matchId, int teamId, string userEmail)

该方法是在 Tournament WebAPI 控制器中定义的,并尝试访问方法并将 HTTP 动词设置为 post,如下所示,

http://localhost:59707/api/tournament/PostMatchBet?tournamentId=1&matchId=1&teamId=8&userEmail=abc@gmail.com

请让我知道我在这里遗漏了什么。

Exception detail: "MessageDetail":"No action was found on the controller 'Tournament' that matches the request."

确保路由配置正确。

public static class WebApiConfig 
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

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

确保动作有正确的动词和路线。您正在混合基于约定和属性的路由。决定你想使用哪一个并坚持下去。

为此 POST URL 工作...

http://localhost:59707/api/tournament/PostMatchBet?tournamentId=1&matchId=1&teamId=8&userEmail=abc@gmail.com

它将匹配基于约定的路由模板,例如

api/{controller}/{action}

映射到此操作。

public class TournamentController : ApiController {
    [HttpPost]
    public HttpResponseMessage PostMatchBet(int tournamentId, int matchId, int teamId, string userEmail) { ... }
}

如果进行属性路由,则需要将控制器更新为...

[RoutePrefix("api/tournament")]
public class TournamentController : ApiController {
    //POST api/tournament/postmatchbet{? matching query strings}
    [HttpPost]
    [Route("PostMatchBet")]
    public HttpResponseMessage PostMatchBet(int tournamentId, int matchId, int teamId, string userEmail) { ... }
}

在您的 URL 路径中

http://localhost:59707/api/tournament/PostMatchBet?tournamentId=1&matchId=1&teamId=8&userEmail=abc@gmail.com

[Route("api/tournament/{tournamentId}/{matchId}/{teamId}/{userEmail}/PostMatchBet")]

如您所见,您应该根据您设置的路线以方法结束。您还说您希望通过斜线分隔而不是参数化 URL 例如(?,&)。因此,如果您传入这样的内容,它将收听它。

http://localhost:59707/api/tournament/1/1/8/abc@gmail.com/PostMatchBet