4

How can I extract the scheme, host, path, and query string from the HTTP Referer using C#?

I'm currently working on a simple ASP.NET Core MVC 6 application and getting the HTTP Referer using Context.Request.Headers["Referer"].ToString().The value of the HTTP referer is http://localhost:5050/Blogs/Details/3 and I'm wondering how I can extract http for the scheme, localhost:5050 for the host (including port), and /Blogs/Details/3 for the path.

Is there anything in ASP.NET Core framework or C# that can do this? Or do I need to manually separate the HTTP Referer string?

1 Answer 1

4

if you save the referrer as a string say refURL = Context.Request.Headers["Referer"].ToString()

Then

var address = new System.Uri(refURL);

var scheme = address.Scheme ;
var host = address.Host;

etc

details on Uri Class

Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately, System.Uri(refURL) doesn't work for ASP.NET Core framework. I'm getting Non-invocable member 'Uri' cannot be used like a method error. I think your solution would work on ASP.NET 4.5 and 4.6, but not on Core.
did you then try the UriBuilder(refURL)
Ok you were right! Both System.Uri and System.UriBuilder work, but I had to create a new instance by using the new keyword (i.e., var address = new System.Uri(refURL);.
Thank you I edited the answer with the new keyword added.. sorry for the confusion
Thanks! I decided to use System.UriBuilder instead of System.Uri because it gave me Path. System.UriBuilder is simpler and exactly what I need. System.Uri has many more properties including AbsolutePath, LocalPath and PathAndQuery, which all have the same Path value, but it seems like overkill for what I'm trying to do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.