具有动态值的 Grapevine Rest Server Route Pathinfo

Grapevine Rest Server Route Pathinfo with dynamic values

我是 C# 的新手,需要实现 REST 服务,所以我无意中发现了 Grapevine。 我需要在服务启动时通过配置文件移交服务的 URL 部分,但我无法将配置文件的值 "clientId" 移交给路由的路径信息,因为它不是持续的。 这是代码的一部分:

[RestResource(BasePath = "/RestService/")]
public class Rest_Resource
{
    public string clientId =  ConfigurationManager.AppSettings["ClientId"];

    [RestRoute(PathInfo = clientId + "/info")]//<-how do I fill Pathinfo with dynamic values?
    public IHttpContext GetVersion(IHttpContext context)
    {....}
    }

我在 visual studio 中使用 grapevine v4.1.1 作为 nuget 包。

虽然可以 change attribute values at runtime, or even use dynamic attributes,但在这种情况下更简单的解决方案可能是不单独使用自动发现功能,而是使用混合方法进行路由注册。

考虑以下 class 包含两条休息路线,但其中只有一条用属性修饰:

[RestResource(BasePath = "/RestService/")]
public class MyRestResources
{
    public IHttpContext ManuallyRegisterMe(IHttpContext context)
    {
        return context;
    }

    [RestRoute(PathInfo = "/autodiscover")]
    public IHttpContext AutoDiscoverMe(IHttpContext context)
    {
        return context;
    }
}

由于您想使用直到运行时才知道的值注册第一个路由,我们可以手动注册该路由:

// Get the runtime value
var clientId = "someValue";

// Get the method info
var mi = typeof(MyRestResources).GetMethod("ManuallyRegisterMe");

// Create the route
var route = new Route(mi, $"/RestService/{clientId}");

// Register the route
server.Router.Register(route);

这会手动注册需要运行时值的路由,但我们仍希望自动发现其他路由。由于路由器只会在服务器启动时路由 table 为空时自动发现,因此我们必须告诉路由器何时扫描程序集。您可以在手动注册路线之前或之后执行此操作:

server.Router.ScanAssemblies();