asp.net mvc 传参问题

 
代码示例:验证两种写法的差异
情况 1:直接用 int Id(无法获取 Body 中的 Id)
csharp
运行

// 前端POST JSON:{"Id": 123} → 这里Id无法绑定,值为0(int默认值)
[HttpPost("info")]
public IResult Info(int Id) 
{
    // Id = 0(未绑定到值)
    return Results.Ok($"Id: {Id}");
}

情况 2:显式指定从 Body 绑定 int Id(可以获取)
如果想直接用int Id并获取 Body 中的值,需要手动加[FromBody]特性(注意:一个 Action 只能有一个[FromBody]参数):
csharp
运行

// 前端POST JSON:{"Id": 123} → 能正常绑定Id=123
[HttpPost("info")]
public IResult Info([FromBody] int Id) 
{
    return Results.Ok($"Id: {Id}");
}

情况 3:用复杂类型(默认从 Body 绑定,推荐)
这是你现在使用的方式,也是行业最佳实践(尤其参数多的时候):
csharp
运行

// 前端POST JSON:{"Id": 123} → 能正常绑定
[HttpPost("info")]
public IResult Info(ApiBookInfoRequest request) 
{
    // request.Id = 123
    return Results.Ok($"Id: {request.Id}");
}

public class ApiBookInfoRequest
{
    public int Id { get; set; }
}

情况 4:Id 放在路由 / 查询字符串(简单类型也能获取)
如果Id是通过路由或查询字符串传递,直接用int Id也能正常获取:
csharp
运行

// 路由传递:POST /info/123 → Id=123
[HttpPost("info/{Id}")]
public IResult Info(int Id) 
{
    return Results.Ok($"Id: {Id}");
}

// 查询字符串传递:POST /info?Id=123 → Id=123
[HttpPost("info")]
public IResult Info(int Id) 
{
    return Results.Ok($"Id: {Id}");
}
 
posted @ 2026-02-04 17:13  云飞扬IT  阅读(0)  评论(0)    收藏  举报