Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 具有不同查询字符串的Web API多重获取操作_C#_.net_Asp.net Web Api - Fatal编程技术网

C# 具有不同查询字符串的Web API多重获取操作

C# 具有不同查询字符串的Web API多重获取操作,c#,.net,asp.net-web-api,C#,.net,Asp.net Web Api,在我的ApicController中,我需要处理以下请求: GET: api/User?role=theRole GET: api/User?division=?theDivision ... GET: api/User?other=stringValue 所有这些请求都可以通过以下方法处理: public HttpResponseMessage Get(String stringParam) 但显然我不能使用重载 我怎样才能解决这个问题?我应该使用一个具有可选参数的单一方法吗?< P>您可

在我的ApicController中,我需要处理以下请求:

GET: api/User?role=theRole
GET: api/User?division=?theDivision
...
GET: api/User?other=stringValue
所有这些请求都可以通过以下方法处理:

public HttpResponseMessage Get(String stringParam)
但显然我不能使用重载


我怎样才能解决这个问题?我应该使用一个具有可选参数的单一方法吗?

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

routes.MapHttpRoute(
名称:“API默认值”,
routeTemplate:“api/{controller}/{id}”,
默认值:新建{id=RouteParameter.Optional}
);

将此更改为

routes.MapHttpRoute(
名称:“API默认值”,
routeTemplate:“api/{controller}/{action}/{id}”,
默认值:新建{id=RouteParameter.Optional}
);

然后,您可以使用正确的HTTP操作(如[HttpGet])标记每个web API操作。要了解有关在Web API中路由和处理多个HTTP操作的更多信息,请根据以下答案查看

:您可以编写如下方法:

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:API/USER StrugPARAM=角色%20TyoL..…/Cord>是的,您只需要用“GET”将该方法的前缀前缀。路由机制将使用查询字符串参数映射到实际方法。