C# .net UriTemplate match url from a whitelist or pool or servers

↘锁芯ラ 提交于 2020-01-07 03:42:16

问题


You can use UriTemplate to parse the url:

I have this code in which locally on localhost:29001 I set the host to be a specific Uri and then I check to if it is a Match

In my real code I do have the the line

var absoluteUri = HttpContext.Current.Request.Url.AbsoluteUri;

of which is used like this

var match = apiTemplate.Match(host, new Uri(absoluteUri));

but essentially this is what the code is going to look like in C# from it running.

var host = new Uri("http://localhost:29001");
var apiTemplate = new UriTemplate("{api}/{*params}", true);

var match = apiTemplate.Match(host, new Uri("http://localhost:29001/GetQAByDateTime/date/2-15-2017/time/11"));
if (match == null)
    throw new ArgumentException();

Console.WriteLine(match.BoundVariables["api"]);     // GetQAByDateTime
Console.WriteLine(match.BoundVariables["params"]);  // date/2-15-2017/time/11

So Essentially I do not want to hardcode the host

  var host = new Uri("http://localhost:29001");

Sure, i can get the server name from the HttpContext but what is the point? Shouldn't I want to check for a pool or servers like

localhost
localhost:290001
https://myserver.com
https://myStagingServer/website
etc..

How can I match on a pool of these?


回答1:


You can extract the host directly fromHttpContext.Current.Request.Url:

var uri = HttpContext.Current.Request.Url;
var host = new Uri(uri.Scheme + "://" + x.Authority);

EDIT: I should add that Uri.Host is avoided because "Unlike the Authority property, this property value does not include the port number."



来源:https://stackoverflow.com/questions/42689379/c-sharp-net-uritemplate-match-url-from-a-whitelist-or-pool-or-servers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!