无法在 MVC Web API 中配置或重写 ASP.NET 路由



我正在开发一个 ASP.NET MVC Web API。我正在为我的 api 重写路由以使 url 整洁。但它不起作用。

我在项目控制器中有这样的操作方法:

public HttpResponseMessage Get([FromUri]string keyword = "", [FromUri]int category = 0, [FromUri]int region = 0, [FromUri]int area = 0, [FromUri]int page = 0,[FromUri]int count = 0)
{
.
.
.
}

在 WebApiConfig 中,我为该操作配置路由,如下所示:

  config.Routes.MapHttpRoute(
            name: "",
            routeTemplate: "api/v1/places/{category}/{region}/{area}/{page}/{count}",
            defaults: new { controller = "ItemsController" , keyword = "" , category = 0 , region = 0 ,area = 0 , page = 0 , count = 0 }
        );

如您所见,我没有在路由中设置关键字。但是当我从下面的 url 访问时,它给了我错误。

这就是我发出获取请求的方式:

http://localhost:50489/api/v1/places/0/0/0/1/2

这是错误:

{
    "Message": "No HTTP resource was found that matches the request URI 'http://localhost:50489/api/v1/places/0/0/0/1/2'.",
    "MessageDetail": "No type was found that matches the controller named 'ItemsController'."
}

如何重写?我想在该网址中设置排除关键字。我也会有另一条路线来行动。

这也不起作用:

config.Routes.MapHttpRoute(
                name: "",
                routeTemplate: "api/v1/places/{keyword}/{category}/{region}/{area}/{page}/{count}",
                defaults: new { controller = "ItemsController" , keyword = "" , category = 0 , region = 0 ,area = 0 , page = 0 , count = 0 }
            );

该错误指示控制器不存在。

这是因为 Web API 正在寻找名为 ItemsControllerController 的控制器。后缀Controller由框架自动添加。因此,如果您的控制器实际上被命名为 ItemsController ,您的路由应该是:

config.Routes.MapHttpRoute(
        name: "",
        routeTemplate: "api/v1/places/{category}/{region}/{area}/{page}/{count}",
        defaults: new { controller = "Items" , keyword = "" , category = 0 , region = 0 ,area = 0 , page = 0 , count = 0 }
    );

下面的虚拟查询尝试使用这种方式。只需进行相应的更改

接口代码:

[Route("api/{Home}/{Username}/{Password}")]
        public HttpResponseMessage Get(string Username, string Password)
        {
//code here
}

WebApiConfig

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            // Web API routes
            config.MapHttpAttributeRoutes();

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

        }
如果您使用的是 Web API 2

ASP.NET 则可以使用 Web API 2 中的@stylishCoder属性路由提供的代码片段 ASP.NET 则可以使用

此链接将帮助您将多个对象传递到终结点。

最新更新