2013-10-22 40 views
0

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

如果我的自定义标题存在,请求将通过,如果标题不存在,则会触发控制器,请求被自定义错误消息拒绝。

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

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

+1

你也许可以使用授权的过滤器或'路由specific'消息处理程序在这种情况下。 –

+0

我没有看到这个门可以做的事情。因为如果您在“http处理程序”或“http模块”或“操作过滤器”中执行此自定义标头的检查。它将运行所有呼叫。也许你可以添加另外一个条件,比如如果某个查询字符串或者cookie存在,那么可以不用自定义头文件 –

+0

实际上@KiranChalla是正确的,你可以像这里一样实现特定于路由的消息处理程序:http:// www。 asp.net/web-api/overview/working-with-http/http-message-handlers – user2818430

回答

0

你可以试试这个。(未经测试)

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


} 
+0

我认为这对于用户所要求的东西来说是一种复杂的方法。 –

+0

我听到你。提供一个简单的(r)响应,我会赞扬它!我全部都是为了学习新东西。 – granadaCoder