首页 > 解决方案 > 多个 get 方法的 API 路由

问题描述

我的 api 中有两个 Get 方法,如下所示:

public IHttpActionResult GetCandidateProfilesByProfileID(long id)
{
......
}

public IHttpActionResult GetCandidatesBySearchCrietria( string FName= null,string LastName = null, Nullable<DateTime> DoB = null, string City = null,string zipCode = null, string stateID = null,string education = null,
{
...
}

如何为这些配置路由?我在使用默认路由调用它们时遇到问题。

谢谢, 马汉特什

标签: apigetroutes

解决方案


我假设您使用的是 Web Api 2。您可以使用Route 属性

为了使 http 属性路由可用,您必须在中添加以下行App_Start\WebApiConfig.cs

static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
    }
}

然后将路由属性添加到方法中。

[HttpGet]
[Route("GetCandidateProfilesByProfileID")]
public IHttpActionResult GetCandidateProfilesByProfileID(long id)
{
    ......
}

[HttpGet]
[Route("GetCandidatesBySearchCrietria")]
public IHttpActionResult GetCandidatesBySearchCrietria( string FName= null,string LastName = null, Nullable<DateTime> DoB = null, string City = null,string zipCode = null, string stateID = null,string education = null)
{
    ...
}

请注意,某些参数是必需的。如果省略这将导致Http 404 Not Found

在 asp.net Core 中,您可以使用HttpGet属性:

[HttpGet("GetCandidateProfilesByProfileID")]
public IHttpActionResult GetCandidateProfilesByProfileID(long id)
{
    ......
}

[HttpGet("GetCandidatesBySearchCrietria")]
public IHttpActionResult GetCandidatesBySearchCrietria( string FName= null,string LastName = null, Nullable<DateTime> DoB = null, string City = null,string zipCode = null, string stateID = null,string education = null)
{
    ...
}

推荐阅读