【问题标题】:Problems when Routing Api路由 Api 时的问题
【发布时间】:2017-09-21 19:27:57
【问题描述】:

我的控制器中有RoutePrefix,例如:

[RoutePrefix("api/Catalogos")]

我有这样的方法:

[System.Web.Http.AllowAnonymous]
[System.Web.Http.HttpGet]
public HttpResponseMessage Get(HttpRequestMessage request)
{
     //some code there
}

所以当我使用邮递员并发送路由时:

http://localhost:55720/api/Catalogos/

它运行没有问题。当我尝试执行另一种方法时,问题就开始了:

[System.Web.Http.AllowAnonymous]
[System.Web.Http.HttpGet]
[Route("GetCatalogo")]
public HttpResponseMessage GetCatalogoPadre(HttpRequestMessage request, string catalogo)
{
      //some code there
}

所以我在邮递员网址中尝试:

http://localhost:55720/api/Catalogos/GetCatalogo/

但我明白了:

{ "Message": "没有找到与请求匹配的 HTTP 资源 URI 'http://localhost:55720/api/Catalogos/GetCatalogo/'。",
"MessageDetail": "在控制器 'Catalogos' 上未找到任何操作 与名称“GetCatalogo”相匹配。”}

为什么我不能路由它?我不明白那里有什么问题。

【问题讨论】:

    标签: c# asp.net-mvc 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: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
    

    并在您的控制器中确保路由已正确配置。

    [RoutePrefix("api/Catalogos")]
    public class CatalogosController : ApiController {
    
        [System.Web.Http.AllowAnonymous]
        [System.Web.Http.HttpGet]
        [Route("")] //Matches GET api/Catalogos
        public HttpResponseMessage Get() {
             HttpRequestMessage request = this.Request;
             //some code there
        }
    
        [System.Web.Http.AllowAnonymous]
        [System.Web.Http.HttpGet]
        [Route("GetCatalogo")] //Matches GET api/Catalogos/GetCatalogo
        public HttpResponseMessage GetCatalogoPadre(string catalogo) {
              HttpRequestMessage request = this.Request;
              //some code there
        }
    
    }
    

    参考Attribute Routing in ASP.NET Web API 2

    【讨论】:

    • 我已经完全按照你的评论,但我仍然无法点击方法
    • 有些异常,其他控制器接受路由,我执行它们没有任何问题。那么whenApiConfig有什么特殊的配置要命中路由吗?
    猜你喜欢
    • 2014-11-27
    • 2013-08-30
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多