ASP.NET Core 中基于标头的路由 [英] Header based routing in ASP.NET Core
问题描述
我正在尝试根据发送到服务的 HTTP 标头将请求路由到不同的控制器.
I'm trying to route requests to different controllers based on a HTTP header sent to the service.
在我的 Configure
方法中,我有
in my Configure
method, I have
app.MapWhen(ctx => !string.IsNullOrWhiteSpace(ctx.Request.Headers["Magic"]), DoStuff);
我的问题是我不知道如何指定控制器,甚至不知道如何修改路由
My issue is that I have no idea how to specify controllers, or even modify the route
private static void DoStuff(IApplicationBuilder app)
{
/// ?!? \
}
理想情况下,如果发送标头 Magic: Missile
,我希望将路由重写为 /Missile
Ideally, I'd like that if the header Magic: Missile
is sent, to rewrite the route to be /Missile
推荐答案
虽然编写自定义中间件当然是一个不错的选择,但另一种选择是创建操作约束(通过实现 IActionContraint 接口).这将允许您使用指示标题的属性来装饰您的方法/必须在请求中提供的值,以便调用给定的方法.
While writing a custom middleware is certainly a good option, another option would be to create an action constraint (by implementing the IActionContraint interface). This would allow you to decorate your methods with an attribute which dictates the header / value that must be provided in the request in order for a given method to be invoked.
我发现这在使用 WebHook 时特别有用,其中外部系统对所有钩子使用单个 URL,并使用标头来区分不同的操作类型.
I found this to be particularly helpful when working with WebHooks where the external system uses a single URL for all hooks, and uses a header to differentiate the different action types.
这个属性的简单实现如下所示:
Here is what a simple implementation of this attribute could look like:
public class HttpHeaderAttribute : Attribute, IActionConstraint
{
public string Header { get; set; }
public string Value { get; set; }
public HttpHeaderAttribute (string header, string value)
{
Header = header;
Value = value;
}
public bool Accept(ActionConstraintContext context)
{
if (context.RouteContext.HttpContext.Request.Headers.TryGetValue(Header, out var value))
{
return value[0] == Value;
}
return false;
}
public int Order => 0;
}
以下是您如何使用它的示例:
And here's a sample of how you could use it:
[HttpPost, Route("webhook"), HttpHeader("X-Drchrono-Event", "PATIENT_CREATE")]
public IActionResult DrChronoPatientCreate(WebHookData data)
{
}
[HttpPost, Route("webhook"), HttpHeader("X-Drchrono-Event", "PATIENT_MODIFY")]
public IActionResult DrChronoPatientModify(WebHookData data)
{
}
这篇关于ASP.NET Core 中基于标头的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!