具有两个GET操作的WebApi控制器

Dor*_*nai 8 c# asp.net-mvc-4 asp.net-web-api

我希望有两个不同的GET操作来查询数据,名称和ID,

我有这些路线:

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

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

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

以及控制器中的这些操作:

    [HttpGet]
    public CompanyModel CompanyId(Guid id)
    {
          //Do something
    }


    [HttpGet]
    public CompanyModel CompanyName(string name)
    {
            //Do something
    }
Run Code Online (Sandbox Code Playgroud)

这样的调用:http://localhost:51119/api/companies/CompanyId/3cd97fbc-524e-47cd-836c-d709e94c5e1e 工作并进入'CompanyId'方法,

一个类似的电话http://localhost:51119/api/companies/CompanyName/something让我找不到404

但是这个:' http://localhost:51119/api/companies/CompanyName/?name=something'工作正常

任何人都可以解释这种行为,我做错了什么?

Dav*_*yon 10

Web API路由选择器无法知道URL末尾的字符串是否为GUID.因此,不是为适当的GET操作选择正确的路径.

为了选择正确的路由,您需要为GUID uri模板添加路由约束.

    public class GuidConstraint : IHttpRouteConstraint
    {
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values,
                          HttpRouteDirection routeDirection)
        {
            if (values.ContainsKey(parameterName))
            {
                string stringValue = values[parameterName] as string;

                if (!string.IsNullOrEmpty(stringValue))
                {
                    Guid guidValue;

                    return Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty);
                }
            }

            return false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后,将约束添加到将处理GUID的路由.

config.Routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = new GuidConstraint() }  // Added
        );
Run Code Online (Sandbox Code Playgroud)

由于此路由比一般"字符串"路由更具体,因此需要将其放置在要解析名称的路径上方.

这应该适当地路由到行动.

希望这可以帮助.

  • [这个问题](http://stackoverflow.com/questions/9569270/custom-method-names-in-asp-net-web-api)可能有助于解释原因.默认情况下,Web API路由遵循REST约定.因此,您可能会看到与普通MVC路由不同的行为. (2认同)