我对C#非常陌生,需要实现REST服务,所以我在小道消息上绊倒了。我需要将服务的部分URL通过配置文件移交给服务启动,但我无法将配置文件的值"clientId“传递给路由的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中使用Grapev4.1.1作为nuget包。
发布于 2017-10-12 15:45:09
虽然在运行时更改属性值甚至可以使用动态属性,但在这种情况下,一个更简单的解决方案可能不是只使用自动发现特性,而是使用混合方法进行路由注册。
考虑以下类,它包含两个rest路由,但其中只有一个是用属性修饰的:
[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();https://stackoverflow.com/questions/46507253
复制相似问题