AES encryption via URL [duplicate] - encryption

How can I decode an encoded URL parameter using C#?
For example, take this URL:
my.aspx?val=%2Fxyz2F

string decodedUrl = Uri.UnescapeDataString(url)
or
string decodedUrl = HttpUtility.UrlDecode(url)
Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:
private static string DecodeUrlString(string url) {
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
return newUrl;
}

Server.UrlDecode(xxxxxxxx)

Have you tried HttpServerUtility.UrlDecode or HttpUtility.UrlDecode?

Try:
var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);

Try this:
string decodedUrl = HttpUtility.UrlDecode("my.aspx?val=%2Fxyz2F");

Related

How to pass array to php url from c#? [duplicate]

Is it possible to pass parameters with an HTTP get request? If so, how should I then do it? I have found an HTTP post requst (link). In that example the string postData is sent to a webserver. I would like to do the same using get instead. Google found this example on HTTP get here. However no parameters are sent to the web server.
My preferred way is this. It handles the escaping and parsing for you.
WebClient webClient = new WebClient();
webClient.QueryString.Add("param1", "value1");
webClient.QueryString.Add("param2", "value2");
string result = webClient.DownloadString("http://theurl.com");
First WebClient is easier to use; GET arguments are specified on the query-string - the only trick is to remember to escape any values:
string address = string.Format(
"http://foobar/somepage?arg1={0}&arg2={1}",
Uri.EscapeDataString("escape me"),
Uri.EscapeDataString("& me !!"));
string text;
using (WebClient client = new WebClient())
{
text = client.DownloadString(address);
}
In a GET request, you pass parameters as part of the query string.
string url = "http://somesite.com?var=12345";
The WebRequest object seems like too much work for me. I prefer to use the WebClient control.
To use this function you just need to create two NameValueCollections holding your parameters and request headers.
Consider the following function:
private static string DoGET(string URL,NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
{
string ResponseText = null;
using (WebClient client = new WebClient())
{
try
{
if (RequestHeaders != null)
{
if (RequestHeaders.Count > 0)
{
foreach (string header in RequestHeaders.AllKeys)
client.Headers.Add(header, RequestHeaders[header]);
}
}
if (QueryStringParameters != null)
{
if (QueryStringParameters.Count > 0)
{
foreach (string parm in QueryStringParameters.AllKeys)
client.QueryString.Add(parm, QueryStringParameters[parm]);
}
}
byte[] ResponseBytes = client.DownloadData(URL);
ResponseText = Encoding.UTF8.GetString(ResponseBytes);
}
catch (WebException exception)
{
if (exception.Response != null)
{
var responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (var reader = new StreamReader(responseStream))
{
Response.Write(reader.ReadToEnd());
}
}
}
}
}
return ResponseText;
}
Add your querystring parameters (if required) as a NameValueCollection like so.
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("id", "123");
QueryStringParameters.Add("category", "A");
Add your http headers (if required) as a NameValueCollection like so.
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("Authorization", "Basic bGF3c2912XBANzg5ITppc2ltCzEF");
GET request with multiple params:
curl --request GET --url
http://localhost:8080/todos/?limit=10&offset=2 --header
'content-type:application/json'
You can also pass value directly via URL.
If you want to call method
public static void calling(string name){....}
then you should call usingHttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create("http://localhost:****/Report/calling?name=Priya);
webrequest.Method = "GET";
webrequest.ContentType = "application/text";
Just make sure you are using ?Object = value in URL

Spring RequestMapping regexp occurrence

I had an url pattern like this:
http://xy.com/param1/value1/param2/value2/..../paramN/valueN
I would like to write a #RequestMapping in Spring colntroller, but I don't know how can I do if I don't know how many param and value will be.
Is there any way to get all params and values to collection?
Or can anybody helpme how to fix this?
Thanks
Why can't you use the standard way without #PathVariables at all? So url will be like
http://xy.com?param1=value1&param2=value2&....&paramN=valueN
and your annotation as:
#RequestMapping("xyz1")
#ResponseBody
public String index(#RequestParam(required = false) String param1, #RequestParam(required = false) String param2,
#RequestParam(required = false) String paramN) {
return "Param1=" + param1 + ", Param2=" + param1 + ", ParamN=" + paramN;
}
#RequestMapping("xyz2")
#ResponseBody
public String index2(HttpServletRequest servletRequest) {
StringBuilder result = new StringBuilder();
for (Entry<String, String[]> entry : servletRequest.getParameterMap().entrySet()) {
result.append(entry.getKey());
result.append('=');
result.append(Arrays.toString(entry.getValue()));
result.append(", ");
}
return result.toString();
}
where #RequestParam is used when all the expected parameters are known and servletRequest.getParameterMap() is used if you really need to handle them dynamically.
Or you can go the hackish way with really optional #PathVariables that is described here.
I was use Spring ModelAttribute instead of

Get parameter from url string

If I have a URL but as a string e.g. www.example.com?q=1234&h=4567 how can I pick out e.g. "q"
I'm picking the url up from a database so I can't use request.querystring("q")
You can use HttpUtility.ParseQueryString:
string url = new Uri("http://www.example.com?q=1234&h=4567").Query;
System.Collections.Specialized.NameValueCollection nvc = System.Web.HttpUtility.ParseQueryString(url);
foreach (string key in nvc.AllKeys)
{
// ...
}
(note that i've added the "http" to the url, otherwise you could not create an Uri)
I would try:
HttpUtility.ParseQueryString(new Uri("http://www.example.com?q=1234&h=4567").Query).Get("q")

Reverse function of HttpUtility.ParseQueryString

.Net's System.Web.HttpUtility class defines the following function to parse a query string into a NameValueCollection:
public static NameValueCollection ParseQueryString(string query);
Is there any function to do the reverse (i.e. to convert a NameValueCollection into a query string)?
System.Collections.Specialized.NameValueCollection does NOT support this, but a derived internal class System.Web.HttpValueCollection DOES (by overriding ToString()).
Unfortunately (being internal) you cannot instantiate this class directly, but one is returned by HttpUtility.ParseQueryString() (and you can call this with String.Empty, but not Null).
Once you have a HttpValueCollection, you can fill it from your original NameValueCollection by calling Add(), before finally calling ToString().
var nameValueCollection = new NameValueCollection {{"a","b"},{"c","d"}};
var httpValueCollection = System.Web.HttpUtility.ParseQueryString(String.Empty);
httpValueCollection.Add(nameValueCollection);
var qs = httpValueCollection.ToString();
nameValueCollection.ToString() = "System.Collections.Specialized.NameValueCollection"
httpValueCollection.ToString() = "a=b&c=d"
A NameValueCollection has an automatic ToString() method that will write all your elements out as a querystring automatically.
you don't need to write your own.
var querystringCollection = HttpUtility.ParseQueryString("test=value1&test=value2");
var output = querystringCollection.ToString();
output = "test=value1&test=value2"
I found that a combination of UriBuilder and HttpUtility classes meets my requirements to manipulate query parameters. The Uri class on its own is not enough, particularly as its Query property is read only.
var uriBuilder = new UriBuilder("http://example.com/something?param1=whatever");
var queryParameters = HttpUtility.ParseQueryString(uriBuilder.Query);
queryParameters.Add("param2", "whatever2");
queryParameters.Add("param3", "whatever2");
uriBuilder.Query = queryParameters.ToString();
var urlString = uriBuilder.Uri.ToString();
The above code results in the URL string: http://example.com/something?param1=whatever&param2=whatever2&param3=whatever2
Note that the ToString() goes via a Uri property, otherwise the output string would have an explicit port 80 in it.
It's nice to be able to do all this using framework classes and not have to write our own code.
I don't think there is a built in one, but here is an example of how to implement http://blog.leekelleher.com/2008/06/06/how-to-convert-namevaluecollection-to-a-query-string/
Here are 2 very useful functions that I use all the time:
private string GetQueryStringParameterValue(Uri url, string key)
{
return HttpUtility.ParseQueryString(url.Query.TrimStart('?'))[key];
}
private Uri SetQueryStringParameterValue(Uri url, string key, string value)
{
var parameters = HttpUtility.ParseQueryString(url.Query.TrimStart('?'));
parameters[key] = value;
var uriBuilder = new UriBuilder(url) { Query = parameters.ToString() };
return uriBuilder.Uri;
}

How can I get the root domain URI in ASP.NET?

Let's say I'm hosting a website at http://www.foobar.com.
Is there a way I can programmatically ascertain "http://www.foobar.com/" in my code behind (i.e. without having to hardcode it in my web config)?
string baseUrl = Request.Url.GetLeftPart(UriPartial.Authority);
Uri::GetLeftPart Method:
The GetLeftPart method returns a string containing the leftmost portion of the URI string, ending with the portion specified by part.
UriPartial Enumeration:
The scheme and authority segments of the URI.
For anyone still wondering, a more complete answer is available at http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/.
public string FullyQualifiedApplicationPath
{
get
{
//Return variable declaration
var appPath = string.Empty;
//Getting the current context of HTTP request
var context = HttpContext.Current;
//Checking the current context content
if (context != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
context.Request.Url.Scheme,
context.Request.Url.Host,
context.Request.Url.Port == 80
? string.Empty
: ":" + context.Request.Url.Port,
context.Request.ApplicationPath);
}
if (!appPath.EndsWith("/"))
appPath += "/";
return appPath;
}
}
HttpContext.Current.Request.Url can get you all the info on the URL. And can break down the url into its fragments.
If example Url is http://www.foobar.com/Page1
HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"
HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"
HttpContext.Current.Request.Url.Scheme; //returns "http/https"
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"
string hostUrl = Request.Url.Scheme + "://" + Request.Url.Host; //should be "http://hostnamehere.com"
To get the entire request URL string:
HttpContext.Current.Request.Url
To get the www.foo.com portion of the request:
HttpContext.Current.Request.Url.Host
Note that you are, to some degree, at the mercy of factors outside your ASP.NET application. If IIS is configured to accept multiple or any host header for your application, then any of those domains which resolved to your application via DNS may show up as the Request Url, depending on which one the user entered.
Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;
host.com => return host.com
s.host.com => return host.com
host.co.uk => return host.co.uk
www.host.co.uk => return host.co.uk
s1.www.host.co.uk => return host.co.uk
--Adding the port can help when running IIS Express
Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port
string domainName = Request.Url.Host
I know this is older but the correct way to do this now is
string Domain = HttpContext.Current.Request.Url.Authority
That will get the DNS or ip address with port for a server.
This works also:
string url = HttpContext.Request.Url.Authority;
C# Example Below:
string scheme = "http://";
string rootUrl = default(string);
if (Request.ServerVariables["HTTPS"].ToString().ToLower() == "on")
{
scheme = "https://";
}
rootUrl = scheme + Request.ServerVariables["SERVER_NAME"].ToString();
string host = Request.Url.Host;
Regex domainReg = new Regex("([^.]+\\.[^.]+)$");
HttpCookie cookie = new HttpCookie(cookieName, "true");
if (domainReg.IsMatch(host))
{
cookieDomain = domainReg.Match(host).Groups[1].Value;
}
This will return specifically what you are asking.
Dim mySiteUrl = Request.Url.Host.ToString()
I know this is an older question. But I needed the same simple answer and this returns exactly what is asked (without the http://).

Resources