【问题标题】:Not able to hit a specific Get method ...Error 404 Not Found无法访问特定的 Get 方法...找不到错误 404
【发布时间】:2012-10-25 08:41:08
【问题描述】:
[HttpGet]
    [ActionName("all")]
    public HttpResponseMessage GetAllCompetitions()
    {
        return Request.CreateResponse(HttpStatusCode.OK, Repository.FindAll());
    }

    [HttpGet]
    [ActionName("GetCompetition")]
    public HttpResponseMessage GetCompetitionById(long id)
    {
        Competition competition = Repository.FindById(id);
        if (competition == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        return Request.CreateResponse(HttpStatusCode.OK, competition);
    }

    [HttpGet]
    [ActionName("format")]
    public HttpResponseMessage format(string postedFormat)
    {
        CompetitionMediaFormat format = (CompetitionMediaFormat)Enum.Parse(typeof(CompetitionMediaFormat), postedFormat, true);

        return Request.CreateResponse(HttpStatusCode.OK, Repository.FindByFormat(format));
    }

我可以点击前两个 get 方法,但是当我点击“格式”方法时,我得到一个 404 Not found 错误

客户端应用调用

var response = await client.GetAsync("api/Competition/format/music");

路由配置

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

请告诉我哪里出错了?

【问题讨论】:

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


    【解决方案1】:

    这是因为参数'postedFormat'的名称,它与您的路由参数名称'id'不匹配。尝试添加一个将postedFormat指定为最后一个参数的路由。

    【讨论】:

    • 感谢它现在有效!不知道我们必须将 HttpGet 方法的参数名称始终设为“id”......方法太多,无法为每个方法添加路由!
    【解决方案2】:

    正如@Justin Harvey 所建议的那样,快速解决方法是。即让你方法

    从这里

    public HttpResponseMessage format(string postedFormat)
    {...}
    

    public HttpResponseMessage format(string id)
    {...}
    

    这是因为默认路由:routeTemplate: "api/{controller}/{action}/{id}", 接受 id

    您可以更改您的路线以接受 postedFormat 作为输入参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      • 2020-08-03
      • 1970-01-01
      • 2021-04-25
      • 2018-07-20
      相关资源
      最近更新 更多