Saturday, March 11, 2017

Url Variable Returns Forward Slash "/" instead of absolute Url in Controller Action

When passing a url from a controller action to an Ajax $.post() result that is to navigate to the landing page, using the code below generates only a forward slash which is the root symbol instead of an absolute url. If the url value (/) will be used in window.location.href, it will cause an IIS page not found error.
var url = new UrlHelper(Request.RequestContext).Action("Index", "Customer");
return Json(new { Url = url });
So, to return the absolute url of the controller action in the current context, replace UrlHelper class with Url.Action() method. It is important to include the Request.Url.Scheme in the parameter to pass the correct protocol of the url. The code below will return an absolute url such as: http://localhost:7088 for the landing page.
var url = this.Url.Action("Index", "Customer", null, Request.Url.Scheme);
return Json(new { Url = url });


Post a Comment