IserviceProvider ปลายทาง WebAPI เพื่อการพัฒนาที่เร็วขึ้นและง่ายขึ้น
หากคุณได้ลงทะเบียนบริการในคอลเลกชันแล้วและต้องการเข้าถึงพวกเขาผ่าน HTTP จากนั้นเพียงแค่แมปจุดสิ้นสุดสากลเช่นนี้:
app . MapServiceProvider ( "services" , builder . Services ) ;
app . Run ( ) ;ตอนนี้คุณสามารถส่งโพสต์/รับคำขอไปยังบริการของคุณเช่น:
GET /services/IYourService/SomeMethod?args=["arg1","arg2","arg3"]
or
POST /services/IYourService/SomeMethod
Content-Type: application/json
["arg1","arg2","arg3"]
คำขอตัวอย่างด้วยยาชื่อสามัญ:
GET /services/IYourService/SomeGenericMethod(Int32)?args=[111,222,333]
คำขอใช้สัญลักษณ์ URL-SAFE สำหรับประเภท ตัวอย่างเช่น พจนานุกรม (String-array (Int32)) เทียบเท่ากับ พจนานุกรม <String, int []>
หากวิธีการของคุณมีอาร์กิวเมนต์ประเภทวัตถุเช่น:
Task < int > ExampleMethod ( object data , CancellationToken cancellationToken ) ;จากนั้นคุณต้องเพิ่มประเภทสำหรับ CAST เป็นพารามิเตอร์เพิ่มเติมในคำขอ:
GET /services/IYourService/ExampleMethod/List(String)?args=[["list_item1","list_item2","list_item3"]]
สำหรับการดาวน์โหลดก็เพียงพอแล้วที่วิธีการส่งคืนวัตถุสตรีม:
Task < Stream > SomeDownloadMethod ( string a , string b , string c , CancellationToken cancellationToken ) ;คำขอดาวน์โหลดจะเป็นเช่นนี้:
GET /services/IYourService/SomeDownloadMethod?args=["argA","argB","argC"]
สำหรับการอัปโหลดวิธีการจะต้องมีอาร์กิวเมนต์ประเภทสตรีม (ตำแหน่งไม่สำคัญ):
Task SomeUploadMethod ( Stream stream , string a , string b , string c , CancellationToken cancellationToken ) ; อัพโหลดคำขอ:
POST /services/IYourService/SomeUploadMethod?args=["argA","argB","argC"]
Content-Type: application/octet-stream
<SomeFileData>
ตัวอย่าง JavaScript:
let file = document . getElementById ( 'some-input' ) . files [ 0 ] ;
let response = await fetch ( '/services/IYourService/SomeUploadMethod?args=' + encodeURIComponent ( JSON . stringify ( [ "argA" , "argB" , "argC" ] ) ) , {
method : 'POST' ,
headers : { 'content-type' : file . type || 'application/octet-stream' } ,
body : file ,
} ) ; หากคุณไม่ต้องการเผยแพร่บริการทั้งหมดในคอลเลกชันให้เพิ่มตัวกรอง:
app . MapServiceProvider ( "services" , builder . Services
. Where ( x => x . ServiceType . Namespace . StartsWith ( "Example" ) ) ) ;หากจำเป็นต้องได้รับอนุญาตจะถูกเพิ่มโดยวิธีมาตรฐานสำหรับ IendPointConventionBuilder:
app . MapServiceProvider ( "services" , builder . Services )
. RequireAuthorization ( ) ;ความปลอดภัยสำหรับวิธีการสามารถเพิ่มผ่านผู้ตรวจสอบผู้ตรวจสอบ:
builder . Services . AddScoped < IExampleService , ExampleService > ( ) ;
builder . Services . Decorate < IExampleService , SecureExampleService > ( ) ; ในการเชื่อมต่อกับ API จากแอปพลิเคชัน. NET อื่นใช้ไคลเอนต์ที่มีอยู่:
using ServiceProviderEndpoint . Client ;
using var client = new SpeClient ( "https://localhost:7149/services" ) ;
var result = await client
. GetService < IYourService > ( )
. SomeMethod ( "arg1" , "arg2" , "arg3" ) ;