How to get the fully qualified server name and port running in mvc 2 using codebehind

In every body I have a question

example if i have url: http: // localhost: 8512 / bookuser / Create

how to get "http: // localhost: 8512" by code in mvc2 ??

give thanks

+3
source share
4 answers

Information on the protocol, host, and port of the request is provided below.

Request.Url.GetLeftPart(UriPartial.Authority)
+8
source

In MVC3, most directly, you can do it like this (it should be pretty accurate): Inside .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));

inside 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 there absoluteUrlBasewill be http://localhost:8512or http://www.contoso.com.

or you can follow the link VoodooChild ...

+2

Try:

Request.Url.AbsoluteUri

It contains information about the requested page.

Also keep this link for future reference.

+1
source

Look at the first "/" after "http: //" - here is a snippet 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();
}}}
-1
source

Source: https://habr.com/ru/post/1786289/


All Articles