C# ASP.NET Web API 中的 FromBody 和 FromUri 属性有什么区别?


当 ASP.NET Web API 调用控制器上的方法时,它必须为参数设置值,这个过程称为参数绑定。

为了绑定模型(一个通常默认为格式化程序的动作参数),从 URI 中,我们需要用 [FromUri] 属性装饰它。FromUriAttribute 继承自 ModelBinderAttribute,它为我们提供了一个快捷指令,指示 Web API 使用 IUriValueProviderFactory 中定义的 ValueProviders 从 URI 中获取特定参数。该属性本身是密封的,无法进一步扩展,但是您可以根据需要添加任意数量的自定义 IUriValueProviderFactories。

[FromBody] 属性继承 ParameterBindingAttribute 类,用于根据 HTTP 请求的主体填充参数及其属性。ASP.NET 运行时将读取主体的责任委托给输入格式化程序。当 [FromBody] 应用于复杂类型参数时,应用于其属性的任何绑定源属性都将被忽略。

FromUri 属性示例

示例

using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public IEnumerable<string> Get([FromUri] string id, [FromUri] string name){
         return new string[]{
            $"The Id of the Student is {id}",
            $"The Name of the Student is {name}"
         };
      }
   }
}

对于上面的示例,让我们在 URI 中传递 id 和 name 的值,以填充到 Get 方法中相应的变量。

https://:58174/api/demo?id=1&name=Mark

输出

以上代码的输出是

FromBody 属性示例

示例

让我们创建一个 Student 模型,它具有以下属性。

namespace DemoWebApplication.Models{
   public class Student{
      public int Id { get; set; }
      public string Name { get; set; }
   }
}

控制器代码

示例

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class DemoController : ApiController{
      public IEnumerable<string> Get([FromBody] Student student){
         return new string[]{
            $"The Id of the Student is {student.Id}",
            $"The Name of the Student is {student.Name}"
         };
      }
   }
}

对于上面的示例,student 的值在请求主体中传递,并映射到 Student 对象的相应属性。以下是使用 Postman 的请求和响应。

更新于:2020-08-19

6K+ 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.