ASP.NET Web API 消息处理程序

本文关键字:消息处理 程序 API Web NET ASP | 更新日期: 2023-09-27 18:36:23

我想实现我的自定义消息处理程序,该处理程序将检查每个请求中必须存在的自定义标头。

如果我的自定义标头存在,则请求

通过,如果标头不存在,则请求将被拒绝并显示自定义错误消息,则会命中控制器。

不,我的

问题是:如果我以这种方式实现我的处理程序,这意味着所有请求都必须具有标头,但是我需要有一个gate,我可以在没有该标头的情况下调用,并且消息处理程序必须忽略该请求并命中控制器即使没有自定义标头。

有可能做到这一点吗?或者我如何实现我的消息处理程序,它将忽略对特定控制器的某些调用或类似的东西......?

ASP.NET Web API 消息处理程序

你可以

试试这个。(未经测试)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

 public abstract class EnforceMyBusinessRulesController : ApiController
{
    protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
    {
        /*
            Use any of these to enforce your rules;
            http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller%28v=vs.108%29.aspx
            Public property Configuration   Gets or sets the HttpConfiguration of the current ApiController.
            Public property ControllerContext   Gets the HttpControllerContext of the current ApiController.
            Public property ModelState  Gets the model state after the model binding process.
            Public property Request Gets or sets the HttpRequestMessage of the current ApiController.
            Public property Url Returns an instance of a UrlHelper, which is used to generate URLs to other APIs.
            Public property User    Returns the current principal associated with this request. 
        */
        base.Initialize(controllerContext);
        bool iDontLikeYou = true; /* Your rules here */
        if (iDontLikeYou)
        {
            throw new HttpResponseException(new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.NotFound));
        }

    }
}

public class ProductsController : EnforceMyBusinessRulesController
{
    protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);
    }

}