Home > Back-end >  C#: How to get a value from a query string containing another url with multiple query params?
C#: How to get a value from a query string containing another url with multiple query params?

Time:01-13

When a url containing a query params that has a URL containing query params like this: https://example.com/login/login.ashx?redirect_url=https://example.com?test=11&test2=22&test3=33

How can I then get https://example.com?test=11&test2=22&test3=33from that Url?

I've tried this with no luck

redirectUrl = HttpUtility.ParseQueryString(HttpUtility.UrlEncode(context.Request.Url.Query)).Get("redirect_url");.

This results in: https://example.com?test=11 and I want https://example.com?test=11&test2=22&test3=33

CodePudding user response:

Any url parameter that contains url string separators should be UrlEncode'd first.

So you need to System.Net.WebUtility.UrlEncode(string value) your parameter url first.

var urlEncodedParameter = System.Net.WebUtility.UrlEncode("https://example.com?test=11&test2=22&test3=33");

then create url

var url = $"https://example.com/login/login.ashx?redirect_url={urlEncodedParameter}";

Then redirect to that. And you will not need to parse that parameter on the controller. It will work on the endpoint with signature like this

public IActionResult Login(string redirect_url)

CodePudding user response:

try this:

string full_url = HttpContext.Request.GetDisplayUrl().ToString();
if (full_url.Contains("redirect_url"))
{
    return full_url.Substring(full_url.LastIndexOf("redirect_url"));
}
return string.Empty;
 
  • Related