【问题标题】:HTTP 404 on invoking my WebAPI method调用我的 WebAPI 方法时的 HTTP 404
【发布时间】:2017-03-19 12:39:54
【问题描述】:

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

方法原型:

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

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

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

请让我知道我在这里缺少什么。

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

【问题讨论】:

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


    【解决方案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) { ... }
    }
    

    【讨论】:

      【解决方案2】:

      在您的 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
      

      【讨论】:

      • URL 中的.com 可能会导致问题,因为它可能被误认为是文件扩展名。
      • 我不知道这会如何发生,因为它的解释是在路由中设置的,结合方法输入应该已经被告知被解释为字符串。你能详细说明一下吗?
      猜你喜欢
      • 1970-01-01
      • 2014-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多