Need c# code to get domain name example ("url: https://stackoverflow.com/questions/ask"). I need output as ("https://stackoverflow.com/")
Asked
Active
Viewed 9,471 times
1
-
are you using this in a controller or in a separate class? You need to show us the code you've attempted – ps2goat Oct 17 '14 at 04:23
-
please answer comments and select the answer that worked as accepted. If neither worked you can leave a comment on any of them. – Scott Selby Oct 17 '14 at 04:54
-
ok... I'll give up my points and vote to close - im just that good a guy – Scott Selby Oct 17 '14 at 05:10
2 Answers
7
next time please try to Google your question to see if it has already been asked and answered. try
var domain = HttpContext.Current.Request.Url.Host;
per comments...
var domain = HttpContextBase.Current.Url.Host;
this can be mocked for unit testing - meaning you can set it to something to test what the code would do .

Scott Selby
- 9,420
- 12
- 57
- 96
-
I wouldn't choose this as the best answer, depending on the architecture. It should be based on a `HttpContextBase` if unit testing is required and/or a disconnected, layered architecture is used. This could be achieved in the controller with `this.HttpContext`. IoC containers can use `new HttpContextWrapper(Http.Context.Current)` to return a compatible `HttpContextBase` object. – ps2goat Oct 17 '14 at 04:28
-
@user3789406, the final slash is not required as a part of the url. If you want it there, concatenate the slash on the end. – ps2goat Oct 17 '14 at 04:29
-
@ps2goat - some times you have to figure that someone is asking how to get the domain ... then you can probably assume their new and just learning and don't need fully testable code, at this stage readable is best , simple is best. – Scott Selby Oct 17 '14 at 04:48
-
true enough. I just remembered that this caused a lot of issues when the team didn't plan for the future and every action referencing `HttpContext.Current` broke the unit tests. – ps2goat Oct 17 '14 at 05:08
-
@ps2goat - did add your comment as well though - you guys actually test code ?? I didn't know people did that in real life :p – Scott Selby Oct 17 '14 at 05:10
-
yes. Unfortunately, tests are added about 6 months after the code and about 2 weeks before the code is re-written. – ps2goat Oct 17 '14 at 05:16
6
You could look into the URI class, which parses a URI into its constituent parts.
For instance:
var uri = new Uri("http://stackoverflow.com/questions/ask");
Debug.WriteLine(uri.Scheme); // "http"
Debug.WriteLine(uri.Host); // "stackoverflow.com"
This would allow you to get what you want like this:
Debug.WriteLine(uri.Scheme + "://" + uri.Host + "/");

Mike Chamberlain
- 39,692
- 27
- 110
- 158
-
one of us misunderstood the question , I thought OP meant the specific Url of the site – Scott Selby Oct 17 '14 at 04:51