WebAPI参数为string、int、double时怎么接收?WebAPI接收参数的方式

本文详细解读了.NETCore WebAPI中参数接收的默认推理规则和如何显式指定接收位置,包括简单类型、实体类、json格式和数据集合的处理方式,并介绍了禁用推理规则后的特殊情况和配置方法。

前言:

.NET Core WebAPI 控制器中接收的参数一般情况下分为简单类型(int、string、double…)、实体类dto、数据集合类型。

事实上,http请求可以把请求参数放到 query、header、form、body 中,而 .NET Core WebAPI 中默认启用了推理规则,可以自动推理参数在哪里并传入控制器参数中。开启默认推理规则时,对于简单类型参数,不能推理出去哪里接收,需要将参数显示指定为 [FromForm] 或者 [FromBody] 等等。

1. 指定参数接收位置的特性

特性绑定源
[FromBody]请求正文
[FromForm]请求正文中的表单数据
[FromHeader]请求标头
[FromQuery]请求查询字符串参数
[FromRoute]当前请求中的路由数据
[FromServices]作为操作参数插入的请求服务

2. 默认规则下接收参数的方式

   /// <summary>
   /// 默认启用参数推理规则时
   /// </summary>
   [Route("api/[controller]/[action]")]
   [ApiController]
   public class TestController : ControllerBase
   {
       [HttpPost]
       public ActionResult AddFormPara1([FromForm]string id)
       {
           //application/x-www-form-urlencoded
           //对于简单类型(string、int),推理不出来,所以需要显示指定参数来源FromForm
           var context = HttpContext.Request;
           return Ok(new { id = id });
       }

       [HttpPost]
       public ActionResult AddFormPara([FromForm] string id, [FromForm] string name)
       {
           //application/x-www-form-urlencoded
           //对于简单类型(string、int),推理不出来,所以需要显示指定参数来源FromForm
           var context = HttpContext.Request;
           return Ok(new { id = id, name = name });
       }

       [HttpPost]
       public IActionResult AddJsonPara1([FromBody] string id)
       {
           //json格式请求过来时Request中的data直接就是id的值,例:data:"111"
           var context = HttpContext.Request;
           return Ok(new { id = id });
       }

       [HttpPost]
       public ActionResult AddJsonPara(dto dto)
       {
           //application/json {"id":"111","name":"winston"}
           var context = HttpContext.Request;
           return Ok(new { id = dto.id, name = dto.name });
       }

       [HttpPost]
       public ActionResult AddJsonParaList(List<dto> dto)
       {
           //application/json [{"id":"111","name":"winston"}]
           var context = HttpContext.Request;
           return Ok(dto);
       }
   
       //[HttpPost]
       //public ActionResult AddJsonPara1([FromBody] string id, [FromBody] string name)
       //{
       //    //这种写法是不行的,FromBody只能指定一个参数
       //    var context = HttpContext.Request;
       //    return Ok(new { id = id, name = name });
       //}
   }

   public class dto
   {
       public string id { get; set; }
       public string name { get; set; }
   }

3. 通过配置SuppressInferBindingSourcesForParameters禁用默认推理规则

services.AddControllers(options => { 
	//其他配置
}).ConfigureApiBehaviorOptions(options =>
{
	//禁用当[FromForm]属性批注时,推理multipart/form-data请求内容类型
	//options.SuppressConsumesConstraintForFormFileParameters = true;
	//禁用api的推理规则,这样就支持post方式直接括号接受参数和model参数方式
	options.SuppressInferBindingSourcesForParameters = true;
});

4. 禁用推理规则后,WebAPI默认从form中取参,此时接参方式

 /// <summary>
 /// 禁用参数推理规则时
 /// </summary>
 [ApiController]
 [Route("api/[controller]/[action]")]
 public class Test1Controller : ControllerBase
 {
     [HttpPost]
     public IActionResult AddFormPara1(string id)
     {
         //application/x-www-form-urlencoded
         //禁用推理规则后,application/x-www-form-urlencoded对于简单类型就不需要显示指定参数来源FromForm
         //但对于application/json的还是接不到
         var context = HttpContext.Request;
         return Ok(new { id = id });
     }

     [HttpPost]
     public IActionResult AddFormPara(string id,string name)
     {
         //application/x-www-form-urlencoded
         //禁用推理规则后,application/x-www-form-urlencoded对于简单类型就不需要显示指定参数来源FromForm
         //但对于application/json的还是接不到
         var context = HttpContext.Request;
         return Ok(new { id = id, name = name });
     }

     [HttpPost]
     public IActionResult AddJsonPara(dto1 dto)
     {
         //application/x-www-form-urlencoded
         //禁用推理规则后,依然可以用实体类来接收json格式数据,但前提是application/x-www-form-urlencoded
         var context = HttpContext.Request;
         return Ok(new { id = dto.id, name = dto.name });
     }

     [HttpPost]
     public IActionResult AddListJsonPara([FromBody]List<dto1> dto)
     {
         //禁用推理规则后,对于json格式数据集合参数,需指定FromBody
         var context = HttpContext.Request;
         return Ok(dto);
     }
 }

 public class dto1
 {
     public string id { get; set; }
     public string name { get; set; }
 }

5. 总结

对于.NET Core WebAPI的默认推理规则,最好还是要开启。针对简单类型,需要显示指定 [FromBody] 或者 [FromForm]。对于json格式参数和数据集合参数按默认规则接收即可。

### 关于 .NET Web API 开发的示例代码与教程 以下是基于提供的引用以及专业知识整理的内容: #### 创建 ASP.NET Web API 项目 可以通过 Visual Studio 的向导快速创建一个新的 ASP.NET Web API 项目。具体操作如下: 1. 打开 Visual Studio 并选择 **文件 -> 新建 -> 项目**。 2. 在弹出的对话框中,依次选择 **Visual C# -> Web -> ASP.NET MVC4 Web 应用程序**[^1]。 完成上述步骤后,即可生成一个基础的 Web API 模板工程。 #### 示例代码:基本 CRUD 功能实现 下面是一个简单的例子,展示如何构建具有增删改查功能的 Web API 控制器。 ```csharp using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace DemoWebAPI.Controllers { public class ProductController : ApiController { static List<Product> products = new List<Product> { new Product { Id = 1, Name = "Apple", Category = "Fruit", Price = 1 }, new Product { Id = 2, Name = "Carrot", Category = "Vegetable", Price = 0.5 } }; // GET api/<controller> public IEnumerable<Product> Get() { return products; } // POST api/<controller> public void Post([FromBody]Product product) { products.Add(product); } // PUT api/<controller>/id public void Put(int id, [FromBody]Product updatedProduct) { var productToUpdate = products.FirstOrDefault(p => p.Id == id); if (productToUpdate != null) { productToUpdate.Name = updatedProduct.Name; productToUpdate.Category = updatedProduct.Category; productToUpdate.Price = updatedProduct.Price; } } // DELETE api/<controller>/id public void Delete(int id) { var productToDelete = products.FirstOrDefault(p => p.Id == id); if (productToDelete != null) { products.Remove(productToDelete); } } } public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public double Price { get; set; } } } ``` 此代码片段展示了如何定义一个 `Product` 类型及其对应的 RESTful 风格接口。 #### 实现依赖注入(DI) 为了提高项目的灵活性和可测试性,可以引入 Autofac 来配置依赖注入容器。以下是如何设置 Autofac 的简单说明: 1. 安装 NuGet 包 `Autofac.Mvc4` 和 `Autofac.WebApi`。 2. 修改 Global.asax.cs 文件中的 Application_Start 方法以注册组件和服务。 ```csharp protected void Application_Start() { var builder = new ContainerBuilder(); // 注册控制器 builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); // 自定义服务注册逻辑... builder.RegisterType<MyService>().As<IMyService>(); IContainer container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); GlobalConfiguration.Configure(WebApiConfig.Register); } ``` 通过这种方式,能够轻松地将业务逻辑层的服务注入到控制器中[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值