未找到带有字符串参数的 Web Api 操作方法
WebApi actionmethod with string parameter notFound
我的控制器中有两个 Get 方法,其中一个有两个字符串参数,第二个有一个字符串参数,但是,当我用一个字符串参数调用方法时,它 returns 404,而带有两个字符串参数的方法工作正常。我想我的路由有问题。
RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapHttpRoute("Login", "api/{controller}/{email}/{password}",
new
{
email = UrlParameter.Optional,
password = UrlParameter.Optional
});
WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
控制器:
[HttpGet]
public IHttpActionResult Validate(string id)
{
//Some code here // doesn't work
}
[HttpGet]
public IHttpActionResult GetCitizen(string email, string password)
{
//Some code here //works fine
}
你能试试属性路由吗?就像,就在您的验证方法上方添加属性
[Route("api/<controllername>/Validate")]
并且在通话时您可以像
http://<localhost>:<port>/api/<controllername>/validate?id=123
希望这对您有所帮助
我的控制器中有两个 Get 方法,其中一个有两个字符串参数,第二个有一个字符串参数,但是,当我用一个字符串参数调用方法时,它 returns 404,而带有两个字符串参数的方法工作正常。我想我的路由有问题。
RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapHttpRoute("Login", "api/{controller}/{email}/{password}",
new
{
email = UrlParameter.Optional,
password = UrlParameter.Optional
});
WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
控制器:
[HttpGet]
public IHttpActionResult Validate(string id)
{
//Some code here // doesn't work
}
[HttpGet]
public IHttpActionResult GetCitizen(string email, string password)
{
//Some code here //works fine
}
你能试试属性路由吗?就像,就在您的验证方法上方添加属性
[Route("api/<controllername>/Validate")]
并且在通话时您可以像
http://<localhost>:<port>/api/<controllername>/validate?id=123
希望这对您有所帮助