Home > Software design >  How to get the url of the current view?
How to get the url of the current view?

Time:09-03

Currently in a razor view I'm doing:

var request = Url.ActionContext.HttpContext.Request;
var builder = new UriBuilder(request.Scheme, request.Host.Host, request.Host.Port.Value, request.Path, request.QueryString.Value);

A problem with the above is that the port and query string might not be available.

Is there a better and shorter way to get the view's url?

CodePudding user response:

If you want to get only the full URL, you can use these two Extension methods

@using Microsoft.AspNetCore.Http.Extensions


string fullUrl1 = Request.GetDisplayUrl();
 //or
string fullUrl2 = Request.GetEncodedUrl();
  • Related