hi every body i have a question
example if i have url : http://localhost:8512/bookuser/Create
how to get "http://localhost:8512" by c开发者_如何学编程ode behind in mvc2 ??
thanks regard
The following will give you the protocol, host and port part of the request
Request.Url.GetLeftPart(UriPartial.Authority)
In MVC3, most directly, You can do it like this (should be pretty same): Within a .cs, You can use code like this:
Uri uri = HttpContext.Current.Request.Url;
String absoluteUrlBase = String.Format(
"{0}://{1}{2}{3}"
uri.Scheme,
uri.Host,
(uri.IsDefaultPort
? ""
: String.Format(":{0}", uri.Port));
within the a .cshtml, You can use
string absoluteUrlBase = String.Format(
"{0}://{1}{2}{3}"
Request.Url.Scheme
Request.Url.Host +
(Request.Url.IsDefaultPort
? ""
: String.Format(":{0}", Request.Url.Port));
In both cases, the absoluteUrlBase
will be http://localhost:8512
or http://www.contoso.com
.
or You can go through the VoodooChild's link...
Try:
Request.Url.AbsoluteUri
This contains information about the page being requested.
Also, keep this link for future reference
Look for the first "/" after the "http://" - here's a piece of code:
public class SName {
private String absUrlStr;
private final static String slash = "/", htMarker = "http://";
public SName (String s) throws Exception {
if (s.startsWith (htMarker)) {
int slIndex = s.substring(htMarker.length()).indexOf(slash);
absUrlStr = (slIndex < 0) ? s : s.substring (0, slIndex + htMarker.length());
} else {
throw new Exception ("[SName] Invalid URL: " + s);
}}
public String toString () {
return "[SName:" + absUrlStr + "]";
}
public static void main (String[] args) {
try {
System.out.println (new SName ("http://localhost:8512/bookuser/Create"));
} catch (Exception ex) {
ex.printStackTrace();
}}}
精彩评论