在.NET Core WebAPI上执行强制性请求标头?

发布于 2025-01-24 08:48:02 字数 231 浏览 0 评论 0原文

是否有一种标准方法来在.NET Core Web API中执行强制性请求标头?我希望所有呼叫者应用程序都可以通过一些跟踪标题,以便我有一些可追溯性的通话量。

我知道,对于Swagger来说,可以通过aperationFilter和自定义标头属性完成。但是对于直接呼叫,我可以想到只使用自定义中间件来强制执行此操作。

这是正确执行此操作的正确方法,还是为此目的可以使用的其他标准方法或标准库?

Is there a standard way to enforce mandatory request headers in .Net Core Web APIs? I want all caller apps to pass some tracking headers so that I have some traceability for call volume.

I am aware that for Swagger, it can be done via OperationFilter and custom header attribute. But for direct calls, I can think of only using custom middleware to enforce this.

Is that the right way to do it or is there other standard way to enforce it or standard libraries available for this purpose?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

别靠近我心 2025-01-31 08:48:02

这里有几种方法可以做到这一点。确实没有一种“标准”方法,但是这些方式非常普遍。

旁边:Swagger/OpenAPI不会改变有关API运行方式的任何事情。也不应该。这些是文档和发现工具。

在项目之外

您可以通过自定义反向代理来执行所需的标头。例如,Apigee允许您自定义其规则,包括为某些URL强制执行标头。这很棒,因为它减轻了项目端点的压力和实施。在这种情况下,应将代理配置为返回400不良请求。

在您的项目中,中间件

在项目代码中,使用ASP.NET中间件是一种解决此问题的方法。您可以创建一个中间件,以检查标头的存在,然后如果丢失了请求,则拒绝它们。

这是一个简单的示例,其中myheader的存在允许调用下一个中间件,但缺乏标头避免调用下一个中间件。

public class HeaderChecker
{
    private readonly RequestDelegate _next;

    public HeaderChecker(RequestDelegate next) => _next = next;

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Headers.ContainsKey("MyHeader"))
            context.Response.StatusCode = 400;
        else
            await _next.Invoke(context);
    }
}

通过注册,您可以将其放置在startup.cs中,

builder.UseMiddleware<HeaderChecker>();

您可以避免使用中间件,但是随后您最终会膨胀控制器的方法,通常会皱眉。无论哪种方法> Q&amp; a 备份了从您的代码中返回400的想法。

在您的项目中,使用[fromheader]

可以使用 [fromheader] 属性,这可能是最简单的方法,尽管这确实意味着您必须将标头绑定到模型。如果您的意图仅仅是为了确保出现标头,并且以任何方式与您的模型无关,那么这可能是不可取的。

与往常一样,在发展中,这取决于。

Here are a few ways to do this. There's not really a "standard" way to do it, but these ways are very common.

Aside: Swagger/OpenAPI does not change anything about how your API operates. Nor should it. Those are documentation and discovery tools.

Outside of your project

You can enforce required headers by customizing your reverse proxy. For example, Apigee allows you to customize its rules, including enforcing headers for certain URLs. This is great because it relieves pressure and implementation on your project's endpoints. The proxy should be configured to return a 400 BAD REQUEST in those cases.

Within your project, Middleware

Within the project's code, using ASP.NET middleware is one way to take care of this. You can create a middleware that checks for the existence of the headers, and then reject the request if they are missing.

Here is a simple example where the existence of MyHeader allows the next middleware to be called, but the lack of the header avoids invoking the next middleware.

public class HeaderChecker
{
    private readonly RequestDelegate _next;

    public HeaderChecker(RequestDelegate next) => _next = next;

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Headers.ContainsKey("MyHeader"))
            context.Response.StatusCode = 400;
        else
            await _next.Invoke(context);
    }
}

with the registration that you would place in Startup.cs

builder.UseMiddleware<HeaderChecker>();

You could avoid the middleware, but then you end up bloating your controller's methods, which is usually frowned on. Either way this SO Q&A backs up the idea of returning the 400 from your code.

Within your project, using [FromHeader]

You can use the [FromHeader] attribute, which is probably the simplest approach that can work, though this does mean you'd have to bind the header to your model. If your intent is simply to ensure a header is present, and not related to your model in any way, then that might not be desirable.

As always, in development, it depends.

甜`诱少女 2025-01-31 08:48:02

如果使用该命令

dotnet swagger tofile

生成Web API的OpenAPI规范,则[fromheader]属性还不够。
一旦添加属性[BINDREQUIRIER],Dotnet Swagger用“必需”:true生成了我的标题字段的规格,

因此我设置了2个属性。

“必需”:true对我们很重要,因为我们正在使用OpenAPI.JSON生成另一个API规范来在服务正在运行的AWS上构建我们的'API Gateway'。

If you use the command

dotnet swagger tofile

to generate the openapi specification of your web api, the [FromHeader] attribute is not enough.
Once I added the attribute [BindRequired], dotnet swagger generated the spec of my header field with "required": true

So I set the 2 attributes.

The "required": true is important for us because we are using the openapi.json to generate another api spec to build our 'Api Gateway' on AWS where the service is running.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文