1

Need c# code to get domain name example ("url: https://stackoverflow.com/questions/ask"). I need output as ("https://stackoverflow.com/")

Community
  • 1
  • 1
Raj Kumar
  • 193
  • 3
  • 9

2 Answers2

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