【问题标题】:Web API multiple GET action with different query strings [duplicate]具有不同查询字符串的 Web API 多个 GET 操作 [重复]
【发布时间】:2015-09-23 15:42:15
【问题描述】:

在我的 ApiController 中,我需要处理这些请求:

GET: api/User?role=theRole
GET: api/User?division=?theDivision
...
GET: api/User?other=stringValue

所有这些请求都可以通过如下方法处理:

public HttpResponseMessage Get(String stringParam)

但显然我不能使用重载...

我该如何解决这种情况?我应该使用带有可选参数的单一方法吗?

【问题讨论】:

  • 您可以考虑将所有参数编码为一个:GET: api/User?stringParam=role%20theRole .....

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


【解决方案1】:

根据这个答案:https://stackoverflow.com/a/12620238/632604 你可以这样写你的方法:

public class UsersController : ApiController
    {

        // GET api/values/5
        public string GetUsersByRole(string role)
        {
            return "Role: " + role;
        }

        public string GetUsersByDivision(string division)
        {
            return "Division: " + division;
        }
    }

Web API 将按照您的要求路由请求:

【讨论】:

  • 是的,您只需在方法名称前加上'Get'前缀。路由机制将使用查询字符串参数映射到实际方法。
【解决方案2】:

您可以考虑做的一件事是修改 WebApiConfig 文件中的默认路由,您将看到默认路由是如何设置为

routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } );

把这个改成

routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );

然后,您可以使用正确的 HTTP 操作(例如 [HttpGet])标记每个 Web API 操作。要了解有关在 Web API 中路由和处理多个 HTTP 操作的更多信息,请查看 http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 1970-01-01
    • 2016-09-22
    • 2018-11-11
    相关资源
    最近更新 更多