简体   繁体   English

将网址视为C#对象,以便我可以拆分参数

[英]Treat url as c# object so I can split params

I want to use a console application to easily divide a URL from its params so I can URL encode the parameters. 我想使用控制台应用程序轻松地从其参数中分隔URL,以便可以对参数进行URL编码。 Is there a type that makes this simple? 有没有可以简化这种类型的类型? Please keep in mind that this is being run outside of a web server. 请记住,此操作正在Web服务器外部运行。

The URL is of the form URL的格式

EG 例如

string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime?PatientID=1234&param2=blah blah blah";

So then I can do 那我就可以

string finalUrl = "http://sitename/folder1/someweb.dll?RetriveTestByDateTime?PatientID=" + HttpUtility.UrlEncode(PatientIDValue) + HttpUtility.UrlEncode(param2Value);

Second, is the second ? 第二,第二? valid? 有效? This data comes from a 3rd party app. 此数据来自第三方应用程序。 Surely this can be accomplished with Regex, but I prefer not to use it as most people on my team do not know regular expressions. 使用Regex当然可以做到这一点,但是我不愿使用它,因为我团队中的大多数人都不知道正则表达式。

Use the Uri class - pass in the string url to the constructor and it will parse out the different parts. 使用Uri类-将字符串url传递给构造函数,它将解析出不同的部分。

The query will be in the Query property and you can reconstruct the URL easily using the Scheme , AbsolutePath and the encoded Query . 该查询将位于Query属性中,您可以使用SchemeAbsolutePath和编码的Query轻松地重建URL。

Firstly your url structure is bad 首先,您的网址结构不正确

string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime?PatientID=1234&param2=blah blah blah";

should be 应该

string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime&PatientID=1234&param2=blah blah blah";

A possible solution, I'm not in a development environment now so this is from the head. 一个可能的解决方案,我现在不在开发环境中,所以这是从头开始的。 Some changes may need to be done to the code. 可能需要对代码进行一些更改。

string url = "http://sitename/folder1/someweb.dll?RetrieveTestByDateTime&PatientID=1234&param2=blah blah blah";
var uri = new Uri(url);
var queryString = uri.Query;
NameValueCollection query = HttpUtility.ParseQueryString(queryString)
query["PatientID"] = string.Concat(HttpUtility.UrlEncode(PatientIDValue), HttpUtility.UrlEncode(param2Value));

// Rebuild the querystring
queryString = "?" + 
                 string.Join("&", 
                              Array.ConvertAll(query.AllKeys, 
                                                key => string.Format("{0}={1}", 
                                                HttpUtility.UrlEncode(key), 
                                                HttpUtility.UrlEncode(query[key]))));

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

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