WebAPI方法获取字符串参数未被调用



我正在创建使用两个获取方法的ASP.NET WebAPI。一个返回所有记录,而另一个应根据称为countryCode的字符串参数进行过滤。我不确定带有字符串参数的GET方法不会被调用。

我尝试了以下URI的

http://localhost:64389/api/team/'GB'
http://localhost:64389/api/team/GB

以下是我的代码

Web API

public HttpResponseMessage Get()
        {
            var teams = _teamServices.GetTeam();
            if (teams != null)
            {
                var teamEntities = teams as List<TeamDto> ?? teams.ToList();
                if (teamEntities.Any())
                    return Request.CreateResponse(HttpStatusCode.OK, teamEntities);
            }
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Team not found");
        }
        public HttpResponseMessage Get(string countryCode)
        {
            if (countryCode != null)
            {
                var team = _teamServices.GetTeamById(countryCode);
                if (team != null)
                    return Request.CreateResponse(HttpStatusCode.OK, team);
            }
            throw new Exception();
        }

webapiconfig

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.JsonFormatter.SupportedMediaTypes
            .Add(new MediaTypeHeaderValue("text/html"));
        }
    }

我认为您可能正在从默认API路由中击中默认的'get()'方法。
我希望如果您将参数名称更改为" ID"这样的" ID",它也可以工作:

public HttpResponseMessage Get(string id)

这是因为默认路由中的可选参数名称为" id"。

对于属性路由工作,您需要用路由配置推断出的值来装饰控制器和方法。
因此,在控制器的顶部,您可能会有:

[RoutePrefix("api/team")]
public class TeamController : ApiController

然后在第二个获得方法上方:

[Route("{countryCode}")]
public HttpResponseMessage Get(string countryCode)

由于属性路由,我没有使用"老式"路由。
在属性路由上查看ASP.NET页面以获取更多信息。

编辑评论:
如果您有两个具有相同参数的路由,则需要以某种方式在路线中区分它们。因此,对于您按团队名称获得的示例,我可能会做这样的事情:

[HttpGet()]
[Route("byTeamName/{teamName}")]
public HttpResponseMessage GetByTeamName(string teamName)
Your url would then be /api/team/byTeamName/...

您的其他方法名称是" get",默认的HTTP属性路由寻找具有与HTTP动词相同的方法名称。但是,您可以将您喜欢的任何方法命名,然后用动词来装饰它们。

最新更新