简体   繁体   English

在ServiceStack中使用正则表达式进行路由

[英]Routing with regular expressions in ServiceStack

I'm trying to build a small .NET Core server with ServiceStack and would like to use regular expressions for routing. 我正在尝试使用ServiceStack构建小型.NET Core服务器,并希望使用正则表达式进行路由。 So far I've basically just created a Hello World project and connected it to database. 到目前为止,我基本上只是创建了一个Hello World项目并将其连接到数据库。

I have these classes in my ServiceModel project: 我的ServiceModel项目中有以下类:

[Route("/hello/{Language}/{Name*}", Matches = @"PathInfo =~ \/hello\/[a-z]{2}\/[A-Za-z]+$")]
public class HelloTo : IReturn<HelloResponse> {
    public string Language { get; set; }
    public string Name { get; set; }
}

[Route("/hello/{Language*}", Matches = @"PathInfo =~ \/hello\/[a-z]{2}$")]
public class Hello : IReturn<HelloResponse> {
    public string Language { get; set; }
}

public class HelloResponse {
    public string Result { get; set; }
}

and this in my ServiceInterface project: 这在我的ServiceInterface项目中:

public HelloResponse Any(HelloTo request) {
    var greeting = Db.SingleById<Greeting>(request.Language);
    return new HelloResponse { Result = $"{greeting.Text}, {request.Name}!" };
}

public HelloResponse Any(Hello request) {
    var greeting = Db.SingleById<Greeting>(request.Language);
    return new HelloResponse { Result = $"{greeting.Text}, you!" };
}

The point is, when I send eg this request: http://localhost/hello/fr , it goes to the first route, even though it has no Name in it. 关键是,当我发送以下请求时: http://localhost/hello/fr ,即使其中没​​有名称 ,它也会转到第一个路由。

As far as I can tell, the second route is inaccesible with this configuration. 据我所知,此配置无法使用第二条路由。 After some experimentation, it seems to me as if the Matches parameter is completely ignored, which makes me think that maybe I need to enable something. 经过一些试验,在我看来好像完全忽略了Matches参数,这使我认为也许我需要启用某些功能。 However, I couldn't find much documentation on this, besides a short note here that routing using regexps should be possible somewhat like this. 但是,除了这里的简短说明,使用regexps进行路由应该有点像这样,我找不到很多文档。

Note that if I changed the second route from Route("/hello/{Language*}" to Route("/hello/{Language}" , this sample will work as expected, presumably because routes without wildcards take precedence, but I need routes ending with wildcards like this for it to be of any practical use. 请注意,如果我将第二条路由从Route("/hello/{Language*}"更改为Route("/hello/{Language}" ,此示例将按预期工作,大概是因为没有通配符的路由具有优先权,但是我需要这样以通配符结尾的路由将具有任何实际用途。

此问题是由于未针对通配符路由验证匹配规则而导致的,现在可以通过此提交解决匹配,在此提交中 ,您的示例将按预期从MyGet上可用的 ServiceStack v5.0.3中正常工作。

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

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