问题
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