HTTP 404在调用我的WebAPI方法时

时间:2017-03-19 12:39:54

标签: c# asp.net-web-api asp.net-web-api-routing

我正在尝试使用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

请让我知道我在这里失踪了什么。

  

异常详细信息:“MessageDetail”:“未找到任何操作   控制器'锦标赛'与请求匹配。“

2 个答案:

答案 0 :(得分:1)

确保路线配置正确完成。

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) { ... }
}

答案 1 :(得分:0)

在您的网址路径

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