.NET - 获取协议、主机和端口 [英] .NET - Get protocol, host, and port

查看:21
本文介绍了.NET - 获取协议、主机和端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET 中是否有一种简单的方法可以快速获取当前协议、主机和端口?例如,如果我在以下 URL 上:

Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:

http://www.mywebsite.com:80/pages/page1.aspx

我需要返回:

http://www.mywebsite.com:80

我知道我可以使用 Request.Url.AbsoluteUri 来获取完整的 URL,我知道我可以使用 Request.Url.Authority 来获取主机和端口,但我不确定在不解析 URL 字符串的情况下获取协议的最佳方法.

I know I can use Request.Url.AbsoluteUri to get the complete URL, and I know I can use Request.Url.Authority to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.

有什么建议吗?

推荐答案

以下 (C#) 代码应该可以解决问题

The following (C#) code should do the trick

Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;

这篇关于.NET - 获取协议、主机和端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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