我对 C#、.NET 或 MVC 模式的了解还不够,无法准确了解此处包含的相关内容,但我正在通过一个非常简单的更改来解决问题。
我有一个带有搜索操作(方法?)的 Controller ,如下所示:
public string Search(int id)
{
return $"The id was {id}";
}
当我到达路线时,我得到了预期的响应,例如
$ curl https://localhost:7180/Players/Search/1
The id was 1
但是当我将变量名从 id
更改为其他任何名称时,行为会发生变化并且由于某种原因该值变为 0。
public string Search(int thing)
{
return $"The thing was {thing}";
}
$ curl https://localhost:7180/Players/Search/1
The thing was 0
我想这可能与模型本身有关,因为模型代码至少有一个 Id
属性
public class Player
{
public int Id { get; set; }
public string? Name { get; set; }
}
但是将该变量重命名为 name
(这看起来很相似)也无济于事。
那么我在这里缺少什么概念?为什么我不能将该变量重命名为我想要的任何名称?提前致谢!
(我不知道如何更好地传达代码的所有不同方面,所以这里是 link to the line in question, inside the project )
最佳答案
默认 MVC 注册(参见 Program
或 Startup
)下一个默认路由,因此它可以绑定(bind)方法的 id
参数作为位置部分路径:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
您可以更改参数名称,例如使用 attribute routing :
[Route("[controller]/search/{thing}")]
public string Search(int thing)
{
return $"The thing was {thing}";
}
或使用 HTTP verb templates :
[HttpGet("[controller]/search/{thing}")]
public string Search(int thing)
{
return $"The thing was {thing}";
}
查看链接文档以获取其他选项/详细信息。
关于C# Controller 行为根据变量名改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74381313/