Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khác biệt giữa FromBody và FromUri trong C# ASP.NET WebAPI

Khi ASP.NET Web API gọi phương thức trên controller, nó phải thiết lập giá trị cho các tham số - quá trình gọi là parameter binding (liên kết tham số).

Để bind một model (tham số action) thường mặc định dùng formatter, từ URI ta cần trang trí nó bằng attribute [FromUri]. FromUriAttribute kế thừa từ ModelBinderAttribute, cung cấp shortcut directive chỉ dẫn Web API lấy tham số cụ thể từ URI sử dụng ValueProviders định nghĩa trong IUriValueProviderFactory. Attribute này là sealed (không thể kế thừa), nhưng ta có thể thêm nhiều custom IUriValueProviderFactories.

Attribute [FromBody] kế thừa ParameterBindingAttribute dùng để điền tham số và thuộc tính từ body của HTTP request. ASP.NET runtime ủy quyền đọc body cho input formatter. Khi [FromBody] áp dụng cho tham số kiểu phức tạp, bất kỳ binding source attributes nào áp dụng cho thuộc tính của nó đều bị bỏ qua.

Ví dụ FromUri Attribute

using System.Collections.Generic;
using System.Web.Http;

namespace DemoWebApplication.Controllers
{
    public class DemoController : ApiController
    {
        public IEnumerable Get([FromUri] string id, [FromUri] string name)
        {
            return new string[]
            {
                $"Id của Student là {id}",
                $"Tên của Student là {name}"
            };
        }
    }
}

Đối với ví dụ trên, truyền giá trị id và name trong URI để populate vào biến tương ứng trong phương thức Get.

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

Kết quả

Khác biệt giữa FromBody và FromUri trong C# ASP.NET WebAPI

Ví dụ FromBody Attribute

Tạo model Student với các thuộc tính sau:

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

Controller Code

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Web.Http;

namespace DemoWebApplication.Controllers
{
    public class DemoController : ApiController
    {
        public IEnumerable Get([FromBody] Student student)
        {
            return new string[]
            {
                $"Id của Student là {student.Id}",
                $"Tên của Student là {student.Name}"
            };
        }
    }
}

Giá trị cho student được truyền trong request body và map vào thuộc tính tương ứng của object Student. Request và response dùng Postman:

Khác biệt giữa FromBody và FromUri trong C# ASP.NET WebAPI