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

csharpserver side programmingprogramming更新于 2025/10/1 22:22:17

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

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

继承自 ParameterBindingAttribute 类的 [FromBody] 属性用于从 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 方法中相应的变量。

http://localhost: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 对象的相应属性。以下是使用 Postman 的请求和响应。


相关文章