amateur
amateur

Reputation: 39

how to get full servername and port running in mvc 2 by codebehind

hi every body i have a question

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

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

thanks regard

Upvotes: 3

Views: 8682

Answers (4)

Matt Stuvysant
Matt Stuvysant

Reputation: 488

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...

Upvotes: 2

William
William

Reputation: 8067

The following will give you the protocol, host and port part of the request

Request.Url.GetLeftPart(UriPartial.Authority)

Upvotes: 9

Manidip Sengupta
Manidip Sengupta

Reputation: 3611

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();
}}}

Upvotes: -1

VoodooChild
VoodooChild

Reputation: 9784

Try:

Request.Url.AbsoluteUri

This contains information about the page being requested.

Also, keep this link for future reference

Upvotes: 1

Related Questions