Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่างระหว่าง FromBody และ FromUri ใน C# ASP.NET WebAPI

Parameter Binding: กระบวนการตั้งค่า Parameter ให้ Controller Method

[FromUri] Attribute

Bind Parameter จาก URI (Query String) ใช้ ModelBinderAttribute ผ่าน IUriValueProviderFactory

public IEnumerable Get([FromUri] string id, [FromUri] string name)
{
    return new string[]
    {
        $"The Id of the Student is {id}",
        $"The Name of the Student is {name}"
    };
}

เรียก: https://localhost:58174/api/demo?id=1&name=Mark

ความแตกต่างระหว่าง FromBody และ FromUri ใน C# ASP.NET WebAPI

[FromBody] Attribute

Bind Parameter จาก Request Body ใช้ Input Formatter อ่าน Body (JSON, XML, Form Data) สำหรับ Complex Type เท่านั้น

// Model
public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// Controller
public IEnumerable Get([FromBody] Student student)
{
    return new string[]
    {
        $"The Id of the Student is {student.Id}",
        $"The Name of the Student is {student.Name}"
    };
}

ส่ง JSON ใน Body ผ่าน Postman:

ความแตกต่างระหว่าง FromBody และ FromUri ใน C# ASP.NET WebAPI

สรุปความแตกต่าง

คุณสมบัติ[FromUri][FromBody]
แหล่งข้อมูลQuery String / Route DataRequest Body
รองรับ TypePrimitive & ComplexComplex Type (แนะนำ)
หลาย Parameterได้หลายตัวได้แค่ 1 ตัวต่อ Request
GET Requestเหมาะสมไม่แนะนำ (บาง Client ไม่ส่ง Body)