2

I am using below piece of code to generate a fully qualified url and pass it back as json for redirection.

returnUrl = Url.Action("ActionName", "Controller", 
                       new RouteValueDictionary(new { type= returnUrl }), 
                       HttpContext.Request.Url.Scheme, 
                       HttpContext.Request.Url.Authority);

returnUrl will initially have a value either type1 or type2 which is why I have given type as returnUrl and then replacing its value with a generated url, but it generates

http://localhost:49518:49518/Controller/ActionName?type=type1
                     //^^^^^ Extra port added

and appends port number 49518 twice. What could be the possible solution to this? Why this is happening?

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200

1 Answers1

1

Just replace HttpContext.Request.Url.Authority with HttpContext.Request.Url.Host.

Because :

  • HttpContext.Request.Url.Authority returns the Domain Name System (DNS) host name or IP address and the port number for a server.
  • HttpContext.Request.Url.Host returns the DNS host name or IP address of the server.

In your code you are using an overload of Url.Action that accept the host name instead of the authority which contains the port.

With this fix your port will be automatically added and there will be not port duplication.

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
  • Will this work as expected in production? I hope it should.. :) – Guruprasad J Rao Feb 23 '16 at 20:01
  • @CodeNotFound - It didn't work for me, on server, it is still returning port number for me. – Shivani May 14 '20 at 04:11
  • @WriteTheCode lol if it didn’t work for you just create your own question on StackOverflow and put it what is not working. For This one it is working for the OP. Thanks and have a good day. – CodeNotFound May 14 '20 at 07:24