【问题标题】:Grapevine Rest Server Route Pathinfo with dynamic values具有动态值的 Grapevine Rest 服务器路由路径信息
【发布时间】:2018-03-12 10:43:18
【问题描述】:

我对 C# 很陌生,需要实现 REST 服务,所以我偶然发现了 Grapevine。 我需要通过配置文件在服务启动时移交服务的部分 URL,但我没有设法将配置文件的值“clientId”移交给 Route 的 Pathinfo,因为它不是恒定的。 以下是部分代码:

[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中使用gravevine v4.1.1作为nuget包。

【问题讨论】:

    标签: c# grapevine


    【解决方案1】:

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

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

    [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);
    

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

    server.Router.ScanAssemblies();
    

    【讨论】:

      猜你喜欢
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多