C# ASP.NET Core Web Api 与 MVC 模式下 body 参数传递,post 参数方式

Visual Studio 2019 + .NET Core 3.1


1WebApiController, 使用 ApiController 标识

[Route("api/[controller]")]

[ApiController]

public class ValuesController : ControllerBase

{

    [HttpPost("GetUser")]

    public UserModel GetUser(UserModel userModel)

    {

        return new UserModel

        {

            UserId = userModel.UserId,

            UserName = userModel.UserName,

        };

    }

}

public class UserModel

{

    public int UserId { get; set; }

    public string UserName { get; set; }

}


POST 支持 json 参数


POST 不支持 form 表单参数




Post 支持 form 表单参数写法 1

使用 [FromForm] 标识

[Route("api/[controller]")]

[ApiController]

public class ValuesController : ControllerBase

{

    [HttpPost("GetUser")]

    public UserModel GetUser([FromForm] UserModel userModel)

    {

        return new UserModel

        {

            UserId = userModel.UserId,

            UserName = userModel.UserName,

        };

    }

}

public class UserModel

{

    public int UserId { get; set; }

    public string UserName { get; set; }

}


只能以 form 表单参数提交,不支持 json 参数



Post 支持 form 表单参数写法 2

使用 [FromForm] 标识

[Route("api/[controller]")]

[ApiController]

public class ValuesController : ControllerBase

{

    [HttpPost("GetUser")]

    public UserModel GetUser([FromForm] int id, [FromForm] string name)

    {

        return new UserModel

        {

            UserId = id,

            UserName = name,

        };

    }

}

public class UserModel

{

    public int UserId { get; set; }

    public string UserName { get; set; }

}


只能以 form 表单参数提交,不支持 json 参数




GET 请求

[Route("api/[controller]")]

[ApiController]

public class ValuesController : ControllerBase

{

    [HttpGet("GetUser")]

    public JsonResult GetUser(string user)

    {

        return new JsonResult(new

        {

            User = user

        });

    }

}





GET 多参数请求

[Route("api/[controller]")]

[ApiController]

public class ValuesController : ControllerBase

{

    [HttpGet("GetUser")]

    public JsonResult GetUser(int id, string name)

    {

        return new JsonResult(new

        {

            Id = id,

            Name = name

        });

    }

}



默认带有 [FromQuery],所以不用额外增加标识

[Route("api/[controller]")]

[ApiController]

public class ValuesController : ControllerBase

{

    [HttpGet("GetUser")]

    public JsonResult GetUser([FromQuery] int id, [FromQuery] string name)

    {

        return new JsonResult(new

        {

            Id = id,

            Name = name

        });

    }

}


2WebApiController, 不使用 ApiController 标识, Route 路由

修改“Startup.cs”文件

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

    if (env.IsDevelopment())

    {

        app.UseDeveloperExceptionPage();

    }

    else

    {

        app.UseExceptionHandler("/Home/Error");

    }

    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>

    {

        endpoints.MapControllerRoute(

            name: "default",

            pattern: "api/{controller=Home}/{action=Index}/{id?}");

    });

}


修改 Controller,使其不用每个接口不用单独设置路由

public class ValuesController : ControllerBase

{

    [HttpPost]

    public UserModel GetUser([FromBody] UserModel userModel)

    {

        return new UserModel

        {

            UserId = userModel.UserId,

            UserName = userModel.UserName,

        };

    }

}

public class UserModel

{

    public int UserId { get; set; }

    public string UserName { get; set; }

}


POST 支持 json 参数


POST 不支持 form 参数


修改 Controller,去掉 [FormBody]

public class ValuesController : ControllerBase

{

    [HttpPost]

    public UserModel GetUser(UserModel userModel)

    {

        return new UserModel

        {

            UserId = userModel.UserId,

            UserName = userModel.UserName,

        };

    }

}

public class UserModel

{

    public int UserId { get; set; }

    public string UserName { get; set; }

}


POST 支持 form参数



POST 不支持 json 参数



GET 请求

public class ValuesController : ControllerBase

{

    [HttpGet]

    public JsonResult GetUser(string user)

    {

        return new JsonResult(new

        {

            User = user

        });

    }

}


GET 多参数请求

public class ValuesController : Controller

{

    [HttpGet]

    public JsonResult GetUser(int id, string name)

    {

        return new JsonResult(new

        {

            Id = id,

            Name = name

        });

    }

}




默认带有 [FromQuery],所以不用额外增加标识

public class ValuesController : ControllerBase

{

    [HttpGet]

    public JsonResult GetUser([FromQuery] int id, [FromQuery] string name)

    {

        return new JsonResult(new

        {

            Id = id,

            Name = name

        });

    }

}


3WebApiController 使用 FromRoute

可以在指定 url 路径上获取请求参数,在自定义业务里经常使用的方法,代码如下:

[Route("api/[controller]")]

[ApiController]

public class ValuesController : ControllerBase

{

    [HttpPost, Route("{user}/products")]

    public JsonResult GetProducts([FromRoute] string user, [FromBody] QueryModel query)

    {

        return new JsonResult(new

        {

            User = user,

            Category = query.Category,

            Data = new List<string>()

            {

                "Apple",

                "Peach"

            }

        });

    }

}

public class QueryModel

{

    public string Category { get; set; }

}




4、MvcController

public class ValuesController : Controller

{

    [HttpPost]

    public UserModel GetUser(UserModel userModel)

    {

        return new UserModel

        {

            UserId = userModel.UserId,

            UserName = userModel.UserName,

        };

    }

}

public class UserModel

{

    public int UserId { get; set; }

    public string UserName { get; set; }

}



POST 支持 form 表单参数

MVC Controller 自动接收 form 表单参数,不使用 [FromForm] 参数也能够接收到前台传递参数



POST 不支持 json 参数


POST 支持 form 表单参数另一种写法

public class ValuesController : Controller

{

    [HttpPost]

    public UserModel GetUser(int id, string name)

    {

        return new UserModel

        {

            UserId = id,

            UserName = name,

        };

    }

}

public class UserModel

{

    public int UserId { get; set; }

    public string UserName { get; set; }

}



POST 支持 json 参数

如果 Mvc Controller 增加 [FromBody] 限定,则不支持表单参数传递,只能传递 json

public class ValuesController : Controller

{

    [HttpPost]

    public UserModel GetUser([FromBody] UserModel userModel)

    {

        return new UserModel

        {

            UserId = userModel.UserId,

            UserName = userModel.UserName,

        };

    }

}

public class UserModel

{

    public int UserId { get; set; }

    public string UserName { get; set; }

}



POST 支持 body 参数

使用 [FormBody] 获取请求参数,不推荐这种方式应用到业务中

public class ValuesController : Controller

{

    public string GetContent([FromBody] string content)

    {

        return content;

    }

}



GET 请求

public class ValuesController : Controller

{

    [HttpGet]

    public JsonResult GetUser(string user)

    {

        return new JsonResult(new

        {

            User = user

        });

    }

}



GET 多参数请求

public class ValuesController : Controller

{

    [HttpGet]

    public JsonResult GetUser([FromQuery] int id, [FromQuery] string name)

    {

        return new JsonResult(new

        {

            Id = id,

            Name = name

        });

    }

}



默认带有 [FromQuery],所以不用额外增加标识

public class ValuesController : Controller

{

    [HttpGet]

    public JsonResult GetUser([FromQuery] int id, [FromQuery] string name)

    {

        return new JsonResult(new

        {

            Id = id,

            Name = name

        });

    }

}


5MvcController 使用 FromRoute


[Route("api/[controller]")]

public class ValuesController : Controller

{

    [HttpPost, Route("{user}/products")]

    public JsonResult GetProducts([FromRoute] string user, [FromBody] QueryModel query)

    {

        return new JsonResult(new

        {

            User = user,

            Category = query.Category,

            Data = new List<string>()

            {

                "Apple",

                "Peach"

            }

        });

    }

}

public class QueryModel

{

    public string Category { get; set; }

}


或者


public class ValuesController : Controller

{

    [HttpPost, Route("api/values/{user}/products")]

    public JsonResult GetProducts([FromRoute] string user, [FromBody] QueryModel query)

    {

        return new JsonResult(new

        {

            User = user,

            Category = query.Category,

            Data = new List<string>()

            {

                "Apple",

                "Peach"

            }

        });

    }

}

public class QueryModel

{

    public string Category { get; set; }

}


注意路由写法,不能使用默认的 {controller}/{action}


总结

1、如果没有使用 UseEndpoints 配的路由则需要使用路指向完整路径

[Route("api/[controller]")]

[HttpPost("GetUser")]

或在方法上指明路由方法的完整路径

[HttpPost, Route("api/values/{user}/products")]

2、作为Api Service,应该选用Web Apijson)模式

3MvcController不建议作为 Api Service 使用

4ASP.NET Core Web Api 不能同时兼容 form 参数与 json 参数,这点与 ASP.NET Framework Web Api 模式不同


作者最新文章
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角
C# Word 转换 PDF 文件,如何转换 PDF