use*_*616 4 c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4
我有一些模型,我想在RazorView中渲染html-markup,如下所示:
<a href="@Model.Website">@Model.Title</a>
Run Code Online (Sandbox Code Playgroud)
用户可以写在任何URL Website属性(google.com,www.google.com,http://www.google.com等).
问题是如果用户不写协议前缀,http那么生成的HTML将被浏览器视为站点相对URL:
<a href="http://localhost:xxxx/google.com">Google</a>
Run Code Online (Sandbox Code Playgroud)
有没有简单的解决方案,还是我必须在渲染html之前准备网站字符串(添加"http"前缀)?
这不是特定于MVC的,但您可以使用UriBuilder该类:
string uri = "http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx";
var uriBuilder = new UriBuilder(uri);
uriBuilder.Scheme = "http";
Console.WriteLine(uriBuilder.Uri);
Run Code Online (Sandbox Code Playgroud)
打印http://msdn.microsoft.com/en-us/library/system.uribuilder.aspx.
string uri = "google.com";
var uriBuilder = new UriBuilder(uri);
uriBuilder.Scheme = "http";
Console.WriteLine(uriBuilder.Uri);
Run Code Online (Sandbox Code Playgroud)
打印http://google.com/.