如何在 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