C# Controller 行为根据变量名改变

标签 c# asp.net-mvc

我对 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

expected behavior when visiting route

但是当我将变量名从 id 更改为其他任何名称时,行为会发生变化并且由于某种原因该值变为 0。

public string Search(int thing)
{
    return $"The thing was {thing}";
}
$ curl https://localhost:7180/Players/Search/1
The thing was 0

unexpected behavior when visiting route

我想这可能与模型本身有关,因为模型代码至少有一个 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 注册(参见 ProgramStartup)下一个默认路由,因此它可以绑定(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/

相关文章:

C# 类型转换 T 其中 T : struct to an interface without boxing

c# - CinchV2 中的模型发生了什么?

c# - 在 catch 子句中尝试 catch

c# - DataMember 属性不影响 json 结果

c# - Mathf.Sign(0) 不返回零

c# - Linq to SQL DataContext 生命周期管理问题

asp.net-mvc - HTTP 错误 500.19 和错误代码 : 0x80070021

asp.net-mvc - ASP MVC 3 cookie 丢失 HttpOnly 和 Secure 标志

asp.net-mvc - 如何使用ASP.NET MVC项目处理HTTP 404

javascript - 如何在 View/PartialView 中正确使用 javascript 命名空间