Computer >> Máy Tính >  >> Lập trình >> C#

Làm cách nào để thêm trình xử lý thông báo tùy chỉnh vào đường dẫn trong Asp.Net webAPI C #?

Để tạo Trình xử lý thông báo HTTP phía máy chủ tùy chỉnh trong API Web ASP.NET, chúng tôi cần tạo một lớp phải được dẫn xuất từ ​​ System.Net.Http.DelectingHandler .

Bước 1 -

Tạo bộ điều khiển và các phương thức hành động tương ứng của nó.

Ví dụ

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;
      }
   }
}

Bước 2 -

Tạo lớp CutomerMessageHandler của riêng chúng tôi.

Ví dụ

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;
      }
   }
}

Chúng tôi đã khai báo lớp CustomMessageHandler bắt nguồn từ DelegateHandlera và bên trong đó chúng tôi đã ghi đè hàm SendAsync ().

Khi một yêu cầu HTTP đến CustomMessageHandler sẽ thực thi và nó sẽ tự trả lại thông báo HTTP mà không cần xử lý thêm yêu cầu HTTP. Cuối cùng, chúng tôi đang ngăn từng và mọi yêu cầu HTTP đạt đến mức cao hơn của nó.

Bước 3 -

Bây giờ hãy đăng ký CustomMessageHandler trong lớp Global.asax.

public class WebApiApplication : System.Web.HttpApplication{
   protected void Application_Start(){
      GlobalConfiguration.Configure(WebApiConfig.Register);
      GlobalConfiguration.Configuration.MessageHandlers.Add(new
      CustomMessageHandler());
   }
}

Bước 4 -

Chạy ứng dụng và cung cấp Url.

Làm cách nào để thêm trình xử lý thông báo tùy chỉnh vào đường dẫn trong Asp.Net webAPI C #?

Từ đầu ra ở trên, chúng ta có thể thấy thông báo mà chúng ta đã đặt trong lớpCustomMessageHandler của chúng ta. Vì vậy, thông báo HTTP không đến được hoạt động Get () và trước đó nó đang quay trở lại lớp CustomMessageHandler của chúng tôi.