来自白名单或池或服务器的C#.net UriTemplate匹配URL [英] C# .net UriTemplate match url from a whitelist or pool or servers

查看:121
本文介绍了来自白名单或池或服务器的C#.net UriTemplate匹配URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用UriTemplate解析网址:

You can use UriTemplate to parse the url:

我有这段代码,其中在localhost:29001上本地将主机设置为特定的Uri,然后检查它是否为Match

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;

像这样使用

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

但是从本质上讲,这就是运行C#时代码的样子.

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

所以本质上我不想hardcode host

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

当然,我可以从HttpContext获取服务器名称,但是有什么意义呢?我是否不应该检查池或类似

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..

如何匹配这些?

推荐答案

您可以直接从HttpContext.Current.Request.Url提取主机:

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

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

我应该补充说避免使用Uri.Host,因为与Authority属性不同,该属性值不包括端口号."

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

这篇关于来自白名单或池或服务器的C#.net UriTemplate匹配URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆