如何在 Asp.Net webAPI C# 中向管道添加自定义消息处理程序?
csharpserver side programmingprogramming更新于 2025/4/14 23:52:17
要在 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 类。

