【问题标题】:How to define a DelegatingHandler for custom route?如何为自定义路由定义 DelegatingHandler?
【发布时间】:2015-06-10 17:26:40
【问题描述】:

我创建了一个 DelegatingHandler,它适用于每个请求。我已经阅读了一些文章,我可以为特定路线定义处理程序,但我尝试了很多方法都没有成功,我错过了一些我没有找到的东西。

最后一次尝试是:

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "SaveMessage",
    routeTemplate: "api/message/{type}",
    defaults: new { type = RouteParameter.Optional },
    constraints: null,
    handler: HttpClientFactory.CreatePipeline(
              new HttpControllerDispatcher(GlobalConfiguration.Configuration), 
              new DelegatingHandler[]{new ValidationHandler()})
);

我的类控制器和方法具有以下属性:

[RoutePrefix("api/message")]
public class MessageController : ApiController
{
    [Route("{type}")]
    [HttpPost]
    public HttpResponseMessage Save(string type, [FromBody] Message message)
    {
        ....
    }
}

我的处理程序缺少什么仅适用于 api/message/text 之类的请求?

我读过How to make more MapHttpRoutes for MVC 4 Apihttp://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection 之类的链接。

【问题讨论】:

  • 那么你是说你的 delegatingHandler 在 api/message/text 路由上工作吗?我认为您已将 Handler 添加到该路由中,因此它应该是这样工作的..
  • 不,它只有在我执行类似 GlobalConfiguration.Configuration.MessageHandlers.Add(new ValidationHandler()) 的操作时才有效,但每个请求都会命中处理程序,我希望 请求 api/message/text 命中处理程序。

标签: c# delegatinghandler


【解决方案1】:

问题是设置为空的约束。 您应该像这样定义它以使其适用于 POST 或 GET:

constraints: new { httpMethod = new System.Web.Http.Routing.HttpMethodConstraint(HttpMethod.Post) }

【讨论】:

  • 如果我有一个类似 api/message/text?token=XXXX 的查询字符串,我应该将它添加到路由配置中吗?
  • 不,查询字符串不是路由的一部分
  • 这是我的浏览器提交的“local.mycompany.com.ar/IntegrationApi/api/message/…”。我也尝试添加 IntegrationApi,但不走运。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
  • 2017-06-01
  • 1970-01-01
  • 2020-02-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多