我正在用两个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"));
}
}
答案 0 :(得分:14)
我认为您可能正在使用默认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谓词相同的方法名称。但是,您可以根据自己喜欢的方式命名方法,并使用动词来装饰它们。