【问题标题】:Set WebApi 2 routes设置 WebApi 2 路由
【发布时间】:2016-05-04 13:55:19
【问题描述】:

我对 WepApi2 和创建 restfull web 服务还很陌生,但我掌握了其中的大部分内容。

最近,我开始开发一个新的 WebApi2,我发现我的一些查询需要一些不可回避的字符,特别是斜杠和反斜杠。

我在这里阅读了几个关于这个问题的教程和问题,但没有一个能满足我,所以我最终设置了这样的 api 查询

http://host/controler/action/?param1=x&param2=y

一切都很完美。我必须为我的操作设置ActionNameRoute 属性,那里没问题,但是一旦我尝试了旧的查询方式

http://host/controller/action/x/y

我总是会收到No action was found on the controller 'Controller' that matches the request.

这是我的路线配置

// Web API configuration and services
            config.MapHttpAttributeRoutes();
            // Web API routes
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{id}",
                defaults: new { controller = "HelloWorld", id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "Config1",
                routeTemplate: "{controller}/{action}/{param1}/{param2}/{param3}",
                defaults: new { controller = "Controller", action = "action", param2 = RouteParameter.Optional, param3 = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "Config2",
                routeTemplate: "{controller}/{param1}/{param2}/{param3}",
                defaults: new { controller = "action", param3 = RouteParameter.Optional }
            );

您可能会注意到我有 2 种配置。嗯,第一种是将动作分类在一个控制器下,这样,将来可以添加更多具有特定动作的控制器,而不是拥有大量具有特定动作的控制器,但是第二种方法是客户想要的.

那么,有没有办法让两种方式一起工作?

编辑:我的错,我忘了展示我的控制器和操作是如何设置的

public class ControllerController : WebApiController
    {
        [Route("Controller/action1/")]
        [ActionName("action1")]
        [HttpGet()]
        public Object action1(string param1, string param2)
        {
            // do action actions code
            return result;
        }

如您所见,除了在配置中设置路由外,我还设置了动作路由属性,但我不知道我可以设置超过 1 个路由属性。将尝试并报告!

【问题讨论】:

  • 在这种情况下,我建议更改为基于属性的路由而不是字符串路由。属性路由允许您在控制器类中分配规则,而不是在基于字符串匹配的单独路由配置中分配规则,并且在处理路由组合时更加健壮。 asp.net/web-api/overview/web-api-routing-and-actions/…
  • 哦,忘了说,请看我的编辑!

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


【解决方案1】:

您可以尝试改用attribute routing

// in your startup configuration:

config.MapHttpAttributeRoutes();

// and your controller:

[RoutePrefix("foo")]
public class FooController
{
    [HttpGet]
    [Route("bar/{param1}/{param2}")]
    [Route("bar")
    public IHttpActionResult GetBar(string param1, string param2)
    {
        // ...
    }
}

【讨论】:

  • 哦,我可以双向设置吗?我确实已经有属性路由,请查看我的编辑,但我不知道它支持超过 1 个设置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
相关资源
最近更新 更多