Stian
Stian

Reputation: 1602

How can I get the current url protocol in the MVC controller?

This method returns the domain and port:

public Uri BuildUrl()
{
    Uri domain = new Uri(Request.GetDisplayUrl());
    return new Uri(domain.Host + (domain.IsDefaultPort ? "" : ":" + domain.Port));
}

But it does not include the "http://" or "https://" part. How can I get it?

Upvotes: 2

Views: 1357

Answers (2)

Roman Marusyk
Roman Marusyk

Reputation: 24609

There is Scheme property

then you can use UriBuilder

var uriBuilder = new UriBuilder(domain.Host)
{
    Scheme = domain.Scheme,
    Port = domain.IsDefaultPort ? -1 : domain.Port
};

return uriBuilder.Uri;

but your method doesn't make any sense, why not use

public Uri BuildUrl() => new Uri(Request.GetDisplayUrl());

Upvotes: 1

Lutti Coelho
Lutti Coelho

Reputation: 2264

You need to get the protocol from Scheme property of Uri.

public Uri BuildUrl()
{
    Uri domain = new Uri(Request.GetDisplayUrl());
    return new Uri(domain.Scheme + "://" + domain.Host + (domain.IsDefaultPort ? "" : ":" + domain.Port));
}

Upvotes: 1

Related Questions