简体   繁体   English

如何检查 controller 和/或操作是否作为来自中间件的有效端点存在?

[英]How do I check if a controller and / or action exists as a valid endpoint from a middleware?

I need to figure out from a middleware if a route or context points to a valid endpoint in my API.我需要从中间件中找出路由或上下文是否指向我的 API 中的有效端点。 I want to do this in order to send a valid json-formatted error response, instead of the default empty error message that the API sends.我想这样做是为了发送有效的 json 格式的错误响应,而不是 API 发送的默认空错误消息。

An alternative solution that figures out that the endpoint resulted in nothing is fine too.另一种解决方案可以确定端点没有任何结果也可以。 My first thought was to use a middleware, but perhaps sending an error with a fall-back controller works too?我的第一个想法是使用中间件,但也许使用回退 controller 发送错误也可以吗?

I would like to give an answer to my own question, as I have found a way to manually check if a route exists.我想回答我自己的问题,因为我找到了一种手动检查路线是否存在的方法。 This was something I did not think of at the time, as I did not realise you could get information about your API through a dependency.这是我当时没有想到的,因为我没有意识到您可以通过依赖项获取有关 API 的信息。

The way I have done this now is to make use of the IActionDescriptorCollectionProvider provider.我现在这样做的方法是利用IActionDescriptorCollectionProvider提供程序。 This will allow me to receive all current routes in the API.这将允许我接收 API 中的所有当前路由。 Using this, I created the following middleware:使用它,我创建了以下中间件:

public async Task InvokeAsync(HttpContext context)
{
    var path = context.Request.Path.Value;
    var routes = _actionDescriptorCollectionProvider.ActionDescriptors.Items.Select(ad => $"/{ad.AttributeRouteInfo.Template}").ToList();

    if (!routes.Any(route => path.Equals(route, StringComparison.InvariantCultureIgnoreCase))) {
        context = await context.HandleRequest(HttpStatusCode.NotFound, "RouteNotFound", "De server heeft geen geldige actie voor de gegeven route.");
        return;
    }

    await _next(context);
}

This fully allows me to respond with a custom error (this is using HandleRequest(), which is an extension of my own), and handle the rest in the frontend.这完全允许我响应自定义错误(这是使用 HandleRequest(),它是我自己的扩展),并在前端处理 rest。

I found another way to solve this to use pre-initialised documentation by the API.我找到了另一种解决此问题的方法,即使用 API 的预初始化文档。 I'm not sure what to call it, but adding the following code to your csproj file creates an XML which gives the same benefits:我不知道该怎么称呼它,但是将以下代码添加到您的 csproj 文件中会创建一个 XML ,它具有相同的好处:

<NoWarn>$(NoWarn);1591</NoWarn>
<DocumentationFile>Files\Documentation\$(Configuration)_$(AssemblyName)_doc.xml</DocumentationFile>

This means that the XML has be parsed of course.这意味着 XML 当然已经被解析了。

I am still looking for different solutions, perhaps better ones if there are problems with this one.我仍在寻找不同的解决方案,如果这个有问题,也许是更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM