如何解决未指定动作名称时为何不调用索引方法
我有一个带有以下控制器的简单ASP.NET Core API:
<base:SceneBase.DataContext>
<sceneGame:SceneGameViewModel />
</base:SceneBase.DataContext>
当我点击URL时:
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type espace:Entity}},Path=X}" />
<Setter Property="Canvas.Top" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type espace:Entity}},Path=Y}" />
<Setter Property="Canvas.ZIndex" Value="{Binding RelativeSource={RelativeSource AncestorType={x:Type espace:Entity}},Path=Z}" />
</Style>
</ItemsControl.ItemContainerStyle>
通过[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
public IActionResult Index()
{
return Ok("index");
}
public IActionResult Get()
{
return Ok("get");
}
}
请求,出现以下错误:
"http://localhost:6001/api/home"
通常,如果我没有指定动作名称,它不应该调用GET
方法吗?
解决方法
两个端点都相同。使用路线来区分它们。例如:
[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
[HttpGet]
public IActionResult Index()
{
return Ok("index");
}
[HttpGet,Route("data")]
public IActionResult Get()
{
return Ok("get");
}
}
这将打开:
http://localhost:6001/api/home/
和
http://localhost:6001/api/home/data
分别使用GET
您还可以更改动词,例如对一个使用HttpGet
,对另一个使用HttpPost
。
在ASP.NET Core API中,操作方法由用作方法属性的HTTP动词(如果未添加,默认为HttpGet
)和用于它。从这种意义上说,您的两种操作方法看起来都类似于路由系统。它看到两个没有路由参数的HttpGet
方法。这就是为什么两种方法都匹配请求的原因-
"http://localhost:6001/api/home"
使路由系统感到困惑,无法选择。这正是错误消息在说什么。
您需要使非默认操作方法更加具体,以便路由机制可以区分两者。像-
[HttpGet("data")]
public IActionResult Get()
{
return Ok("get");
}
现在,您的Index
方法将与上述URL匹配为默认操作方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。