[英]How to handle cancellation in Controller actions in ASP.NET Web API?
[英]ASP.NET Web API routes not mapping to controller actions
我有一个ASP.NET Web API应用程序,我想在其中响应以下路由:
1. http://localhost:1234/values
2. http://localhost:1234/values/123
3. http://localhost:1234/values/large
4. http://localhost:1234/values/small
注意:这些路线和示例仅是示例。 但是他们映射到我想要实现的目标。
与十亿个ASP.NET Web Api路由示例一样,数字(1)和(2)很简单。 但是,当我尝试解决(3)和(4)时,(1)和(2)不再起作用。
这是我目前的路线:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// trying to map to "values/large" or "values/small"
routes.MapHttpRoute(
name: "ActionsApi",
routeTemplate: "{controller}/{action}",
defaults: null,
constraints: new { action = @"^[a-zA-Z]+$" }
);
// trying to map to "values/123"
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: null,
constraints: new { id = @"^\d+$" }
);
// trying to map to "values"
routes.MapHttpRoute(
name: "ControllerApi",
routeTemplate: "{controller}"
);
通过以上路线,(3)和(4)起作用。
(2)返回:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
No action was found on the controller 'Values' that matches the name '123'.
</string>
并且(1)返回:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
Multiple actions were found that match the request:
System.Collections.Generic.IEnumerable`1[System.String] Get() on type MvcApplication3.Controllers.ValuesController
System.Collections.Generic.IEnumerable`1[System.String] Large() on type MvcApplication3.Controllers.ValuesController
System.Collections.Generic.IEnumerable`1[System.String] Small() on type MvcApplication3.Controllers.ValuesController
</string>
我对于如何设置路由以支持上面列出的4个API示例感到困惑。
编辑:感谢戴维,他指出\\ w也匹配数字,因此是一个问题。 我将其更改为[a-zA-Z] +以匹配大和小 。
现在除(1)以外的所有工作。
编辑2如@andrei所建议,我将id参数设置为可选,以尝试使(1)工作,但导致该路由出现以下错误:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
我在此处添加的可选默认值:
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^\d+$" }
);
您是否考虑过将路由保留为默认设置,并在控制器中处理“值”?
例如,更改Get以使ID为字符串类型,然后检查控制器内部的“特殊”值。
public class ValuesController : ApiController
{
// GET api/values/5
public string Get(string id)
{
if (id == "large")
{
return "large value";
}
if (id == "small")
{
return "small value";
}
return "value " + id;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.