If you include a query string on the HREF of the "Launch" link on the publish.htm page that ClickOnce generates when you publish a Windows desktop application:
HREF="MyWindowsApp.application?ARG1=sis&ARG2=boom&ARG3=bah"
then the query string can be accessed and parsed inside the Windows program:
if (ApplicationDeployment.IsNetworkDeployed)
{
string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
nameValueColl = System.Web.HttpUtility.ParseQueryString(queryString);
}
But the NameValueCollection that the HttpUtility parser returns is case-sensitive. A parameter won't be found if you test for it using the wrong case:
if (ApplicationDeployment.IsNetworkDeployed)
{
string queryString = ApplicationDeployment.CurrentDeployment.ActivationUri.Query;
nameValueColl = System.Web.HttpUtility.ParseQueryString(queryString);
if (nameValueColl.AllKeys.Contains("arg1") )
{
// we don't get here
}
}
Is there an alternative to System.Web.HttpUtility.ParseQueryString that uses a case-insensitive comparer?
This is my string
string link = "http%3A%2F%2Feurocommunicator.ge%2Fgeo%2Fview_myth%2F229"
I want to get absolute uri but it throws exception that uri is invalid :
Uri uri = new Uri(link);
What's wrong in this sting?
i want to get something like this :
http://eurocommunicator.ge/geo/view_myth/229
You can use :
string decodedUrl = Uri.UnescapeDataString(url)
https://msdn.microsoft.com/en-us/library/system.uri.unescapedatastring(v=vs.110).aspx
Works like a charm in linqpad
void Main()
{
var url="http%3A%2F%2Feurocommunicator.ge%2Fgeo%2Fview_myth%2F229";
string decodedUrl = Uri.UnescapeDataString(url);
Console.WriteLine(decodedUrl);
}
You can try doing this:
Uri uri = new Uri("http://eurocommunicator.ge/geo/view_myth/229");
or
string link = "http%3A%2F%2Feurocommunicator.ge%2Fgeo%2Fview_myth%2F229"
Uri uri = new Uri(Server.UrlDecode(link));
Ok ok my fail HttpUtility.UrlDecode works fine, i was using HtmlDecode instead of it. How stupid am i
I'm trying to retrieve the URL of the current page via a Web Method. The code below works well on a normal C# Method such as the Page_Load but does not work inside a Web Method.
[WebMethod(EnableSession=true)]
public static void UpdateProjectName(string name)
{
string project_id = HttpContext.Current.Request.Url.ToString();
}
I'm receiving an empty string ("") as the project_id. What am I doing wrong?
You need this:
[WebMethod]
public static string mywebmethod()
{
string myUrl= HttpContext.Current.Request.UrlReferrer.PathAndQuery.ToString();
return parameters
}
Try to do next code:
[WebMethod(EnableSession=true)]
public static void UpdateProjectName(string name)
{
string project_id = HttpContext.Current.Request.Url.AbsoluteUri.ToString();
}
Url is just object, that's why it returns empty value to you. AbsoluteUri will give a full URL of current page. Example: http://yourweb.site/Admin.aspx?id=15&time=yesterday
To get information of the client's previews request to current website you can use the UrlReferrer as follow:
//To get the Absolute path of the URI use this
string myPreviousAbsolutePath = Page.Request.UrlReferrer.AbsolutePath;
//To get the Path and Query of the URI use this
string myPreviousPathAndQuery = Page.Request.UrlReferrer.PathAndQuery;
I have a multiple lines textbox that allows the users to enter comments. These comments will be sent via a WCF REST method call to store in the SQL DB. The comment can be empty as well.
here is the exception details that I was able to capture in the error log:
Message: The remote server returned an error: (404) Not Found.
StackTrace:
at System.Net.HttpWebRequest.GetResponse()
at Portal.WebServiceFacade.RESTClient.LeaveManagementCRUDOperations(String employeeId, String companyName, String leaveStartDate, String leaveEndDate, String rejoiningDate, String leaveCode, String comments, String userId, String leavePayment, String isPostedInGP, String availableLeaveBalance, String CRUDParameter)
at Portal.WebServiceFacade.LeaveEntityWebService.LeaveManagementSaveOperation(String siteUrl, String employeeId, String companyName, String leaveStartDate, String leaveEndDate, String leaveCode, String comments, String leavePayment, String availableLeaveBalance)
Right now if the comment contains a '/' '\' or a '#' character, it's crashing the REST method.
The UI is a SharePoint custom web part hence we have full control over the code.
How can I achieve this validation upon the submit button click?
Update After Enigmativity's Uri DataEscape Method Solution
I changed the code that creates the Uri as the answer and got the same error. Code and the output shown below:
Code
private const string ParameterUrlStringFormat = "/{0}";
private const string RESTMethodUriFormat = "{0}/_vti_bin/" + RESTClient.RestServiceName + "/{1}{2}";
private HttpWebRequest CreateWebRequest(string methodName, List<string> parameterCollection)
{
StringBuilder parameterUrlStringBuilder = new StringBuilder();
foreach (string parameter in parameterCollection)
{
parameterUrlStringBuilder.Append(string.Format(RESTClient.ParameterUrlStringFormat,
Uri.EscapeDataString(parameter)));
}
string requestUriString = string.Format(RESTClient.RESTMethodUriFormat, SiteUrl,
methodName, parameterUrlStringBuilder.ToString());
LogHelper.LogULSException("Escaped Uri: " + requestUriString);
var request = GenerateHttpWebRequest(requestUriString);
return request;
}
The comment was
Testing Parameter DataEscape for / and \ and #
Output in the log:
Debug Message: Escaped Uri: http://my-dev/HR/_vti_bin/PortalRestWcfService.svc/LeaveManagementCRUDOperations/SRK00051/Head%20Office/2015-08-29/2015-08-29/1900-01-01/2/Testing%20Parameter%20DataEscape%20for%20%2F%20and%20%5C%20and%20%23/SRK00051/1/0/52/1
So it appears that you are building your URL using illegal characters. Since you haven't provided any code it is hard to say exactly how you are doing it, but you probably need to escape the characters and not avoid them. You've identified some illegal characters, but there are many more.
Try this:
var safe = Uri.EscapeDataString(#"this/is\some#text")
The value of sale becomes:
this%2Fis%5Csome%23text
You should be able to use that for creating your call.
Somewhere in the url there is a &sortBy=6 . How do I update this to &sortBy=4 or &sortBy=2 on a button click? Do I need to write custom string functions to create the correct redirect url?
If I just need to append a query string variable I would do
string completeUrl = HttpContext.Current.Request.Url.AbsoluteUri + "&" + ...
Response.Redirect(completeUrl);
But what I want to do is modify an existing querystring variable.
To modify an existing QueryString value use this approach:
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set("sortBy", "4");
string url = Request.Url.AbsolutePath;
Response.Redirect(url + "?" + nameValues); // ToString() is called implicitly
I go into more detail in another response.
Retrieve the querystring of sortby, then perform string replace on the full Url as follow:
string sUrl = *retrieve the required complete url*
string sCurrentValue = Request.QueryString["sortby"];
sUrl = sUrl.Replace("&sortby=" + sCurrentValue, "&sortby=" + newvalue);
Let me know how it goes :)
Good luck
private void UpdateQueryString(string queryString, string value)
{
PropertyInfo isreadonly = typeof(System.Collections.Specialized.NameValueCollection).GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
isreadonly.SetValue(this.Request.QueryString, false, null);
this.Request.QueryString.Set(queryString, value);
isreadonly.SetValue(this.Request.QueryString, true, null);
}
If you really want this you need to redirect to new same page with changed query string as already people answered. This will again load your page,loading page again just for changing querystring that is not good practice.
But Why do you need this?
If you want to change the value of sortBy from 6 to 4 to use everywhere in the application, my suggession is to store the value of query string into some variable or view state and use that view state everywhere.
For e.g.
in Page_Load you can write
if (!IsPostBack)
{
ViewState["SortBy"] = Request.QueryString["sortBy"];
}
and everywhere else ( even after postback ) you can use ViewState["SortBy"]
Based on Ahmad Solution I have created following Method that can be used generally
private string ModifyQueryStringValue(string p_Name, string p_NewValue)
{
var nameValues = HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set(p_Name, p_NewValue);
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
return url + updatedQueryString;
}
and then us it as follows
Response.Redirect(ModifyQueryStringValue("SortBy","4"));
You need to redirect to a new URL. If you need to do some work on the server before redirecting there you need to use Response.Redirect(...) in your code. If you do not need to do work on the server just use HyperLink and render it in advance.
If you are asking about constructing the actual URL I am not aware of any built-in functions that can do the job. You can use constants for your Paths and QueryString arguments to avoid repeating them all over your code.
The UriBuilder can help you building the URL but not the query string
You can do it clientside with some javascript to build the query string and redirect the page using windows.open.
Otherwise you can use Response.Redirect or Server.Transfer on the server-side.
SolrNet has some very helpful Url extension methods. http://code.google.com/p/solrnet/source/browse/trunk/SampleSolrApp/Helpers/UrlHelperExtensions.cs?r=512
/// <summary>
/// Sets/changes an url's query string parameter.
/// </summary>
/// <param name="helper"></param>
/// <param name="url">URL to process</param>
/// <param name="key">Query string parameter key to set/change</param>
/// <param name="value">Query string parameter value</param>
/// <returns>Resulting URL</returns>
public static string SetParameter(this UrlHelper helper, string url, string key, string value) {
return helper.SetParameters(url, new Dictionary<string, object> {
{key, value}
});
}
The only way you have to change the QueryString is to redirect to the same page with the new QueryString:
Response.Redirect("YourPage.aspx?&sortBy=4")
http://msdn.microsoft.com/en-us/library/a8wa7sdt(v=vs.100).aspx
I think you could perform a replacement of the query string in the following fashion on your server side code.
NameValueCollection filtered = new NameValueCollection(request.QueryString);
filtered.Remove("SortBy");
filtered.Add("SortBy","4");
The query string is passed TO the server. You can deal with the query string as a string all you like - but it won't do anything until the page is ready to read it again (i.e. sent back to the server). So if you're asking how to deal with the value of a query string you just simply access it Request.QueryString["key"]. If you're wanting this 'change' in query string to be considered by the server you just need to effectively reload the page with the new value. So construct the url again page.aspx?id=30 for example, and pass this into a redirect method.