如何在 Asp.Net webAPI C# 中向管道新增自定義訊息處理程式?
要建立 ASP.NET Web API 中的自定義伺服器端 HTTP 訊息處理程式,我們需要建立一個必須從System.Net.Http.DelegatingHandler派生的類。
步驟 1 -
建立一個控制器及其對應的操作方法。
示例
using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
public class StudentController : ApiController{
List<Student> students = new List<Student>{
new Student{
Id = 1,
Name = "Mark"
},
new Student{
Id = 2,
Name = "John"
}
};
public IEnumerable<Student> Get(){
return students;
}
public Student Get(int id){
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
}步驟 2 -
建立我們自己的 CutomerMessageHandler 類。
示例
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DemoWebApplication{
public class CustomMessageHandler : DelegatingHandler{
protected async override Task<HttpResponseMessage>
SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){
var response = new HttpResponseMessage(HttpStatusCode.OK){
Content = new StringContent("Result through custom message handler..")
};
var taskCompletionSource = new
TaskCompletionSource<HttpResponseMessage>();
taskCompletionSource.SetResult(response);
return await taskCompletionSource.Task;
}
}
}我們已宣告從 DelegatingHandler 派生的 CustomMessageHandler 類,並在其中覆蓋了 SendAsync() 函式。
當 HTTP 請求到達時,CustomMessageHandler 將執行,並且它將自行返回一個 HTTP 訊息,而不會進一步處理 HTTP 請求。因此,最終我們阻止了每個 HTTP 請求到達其更高級別。
步驟 3 -
現在在 Global.asax 類中註冊 CustomMessageHandler。
public class WebApiApplication : System.Web.HttpApplication{
protected void Application_Start(){
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.MessageHandlers.Add(new
CustomMessageHandler());
}
}步驟 4 -
執行應用程式並提供 URL。

從以上輸出中,我們可以看到我們在 CustomMessageHandler 類中設定的訊息。因此,HTTP 訊息沒有到達 Get() 操作,並且在此之前它返回到我們的 CustomMessageHandler 類。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP