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.