how to get complete url and base url in MVC?


How can I get complete and base type of URL in C# asp.net MVC web-application, controller, for example, if my web-application URL is https://qawithexperts.com/questions/111/invalid-uri-the-format-of-the-uri-could-not-be-determined-er

https://qawithexperts.com //base url

https://qawithexperts.com/questions/111/invalid-uri-the-format-of-the-uri-could-not-be-determined-er // complete url

/questions/111/invalid-uri-the-format-of-the-uri-could-not-be-determined-er // after base part of it

how can I get all types of URL in C#?

I would like to save "after base part" of URL in database for some purpose, thanks


Asked by:- manish
2
: 209 At:- 9/16/2017 10:29:15 AM
MVC asp.net url uri iis






2 Answers
profileImage Answered by:- pika

You can get the base Url(https://qawithexperts.com) in C# using the code below

//Get request from Current HttpContext
var request = HttpContext.Current.Request;

//request.Url.Scheme gives output as https/http 
//while request.Url.Authority give us Domain name
var baseUrl= request.Url.Scheme+"://"+ request.Url.Authority;

Continuing the above code, you can get absolute URL(or you can say after base URL, ie. like /questions/111/invalid-uri-the-format-of-the-uri-could-not-be-determined-er ) using the code below

request.Path; //gives you absolute URL

//or

request.Url.AbsolutePath; // also does the same thing to provide you '/questions/112/how-to-get-complete-url-and-base-url-in-mvc'

Using the above C# asp.net code you can save these URL (absolute & web-base url) in database or do something else with them.

2
At:- 9/19/2017 10:54:43 AM
thanks i was looking for same details to get base url in c# 1
By : Sam - at :- 9/19/2017 4:53:21 PM
thank you 0
By : manish - at :- 9/28/2017 3:22:56 PM


profileImage Answered by:- Vipin

You can create a function like this in C# to get Complete URL, base URL and absolute URL

public string GetBaseUrl()
{
    var request = HttpContext.Current.Request;
    var appUrl = HttpRuntime.AppDomainAppVirtualPath;

    if (appUrl != "/") 
        appUrl = "/" + appUrl;

    var baseUrl = string.Format("{0}://{1}{2}",
 request.Url.Scheme, //request.Url.Scheme gives https or http
request.Url.Authority, //request.Url.Authority gives qawithexperts/com
 appUrl); //appUrl = /questions/111/ok-this-is-url

    return baseUrl; //this will return complete url
}
1
At:- 9/30/2017 8:38:41 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use