I have taken over a project that has a lot of code that is concatenating strings to put together a url. I keep struggling to remember if each of these APIs return the “/” at the end of the base Url (either “http://www.mysite.com” or “http://www.mysite.com/”)
For example:
var baseUrl = "http://www.mySite.com/";
var controllerAndAction = "/Mycontroller/MyAction";
var fullUrl = baseUrl + controllerAndAction;
or
var baseUrl = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
var controllerAndAction = "Mycontroller/MyAction";
var fullUrl = baseUrl + controllerAndAction;
or
var baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
var controllerAndAction = "Mycontroller/MyAction";
var fullUrl = baseUrl + controllerAndAction;
or
var baseUrl = "http://www.mySite.com";
var controllerAndAction = "/Mycontroller/MyAction";
var fullUrl = baseUrl + controllerAndAction;
(Notice the “/”s at the end of baseUrl and at the beginning of controllerAndAction)
I am trying to figure out the cleanest way to make sure these create proper Urls that include a single “/” (not 2 or 0)
is there anything i can do to help confirm this (besides manually testing each one . .) ?
NOTE:
i need this code to work in an asp.net-mvc and a winforms project so i am trying to avoid code that is coupled to either one (to avoid referencing unnecessary libraries)
That isn’t fun. Check out Path.Combine for Urls. This method should allow you to combine base urls, paths and query strings.
Note: The link suggests using a
URIwhich is a base system class, available in any type of C#/VB project.