asp.net-web-api – Webapi方法获取字符串参数未被调用

我用两个get方法创建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”,那么它也会起作用:

public HttpResponseMessage Get(string id)

这是因为默认路由中的可选参数名称是“id”.

要使属性路由起作用,您需要使用先前由路由配置推断的值来装饰控制器和方法.
因此,在控制器的顶部,您可能会:

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

然后在你的第二个get方法之上:

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

由于属性路由,我没有使用“旧式”路由.
查看ASP.NET page on attribute routing以获取更多信息.

编辑评论:
如果您有两条具有相同参数的路线,则需要在路线中以某种方式区分它们.所以对于你的团队名称获取的例子,我可能会这样做:

[HttpGet()]
[Route("byTeamName/{teamName}")]
public HttpResponseMessage GetByTeamName(string teamName)

Your url would then be /api/team/byTeamName/...

您的其他方法名称为“Get”,默认HTTP属性路由查找与HTTP谓词相同的方法名称.但是,您可以根据自己喜欢的方式命名方法,并使用动词来装饰它们.

相关文章

引言 本文从Linux小白的视角, 在CentOS 7.x服务器上搭建一个...
引言: 多线程编程/异步编程非常复杂,有很多概念和工具需要...
一. 宏观概念 ASP.NET Core Middleware是在应用程序处理管道...
背景 在.Net和C#中运行异步代码相当简单,因为我们有时候需要...
HTTP基本认证 在HTTP中,HTTP基本认证(Basic Authenticatio...
1.Linq 执行多列排序 OrderBy的意义是按照指定顺序排序,连续...