I'm working on a project that call a WebMethod dynamically after validating its parameters by knowing its URL.
Here's my attempt:
[WebMethod]
public string CalledService (string myText, int count)
{
return myText;
}
and all I know is its URL
http://localhost:29740/OnewayWebserviceCall/WebService.asmx?op=CalledService
I need a function that returns something like {"myText","count"}
I tried to download the URL string and search for the parameters in it but I need something more time efficient.
Related
I am trying to get parameter form a View and passing it to the controller:
[HttpPost]
public string GetWord()
{
string word = Request["word"];
return word;
}
But I got an error
Indexing using the [] construct cannot be used for an Http Request expression
I looked at documentation and I don't know why it is not working. What should I do to fix this?
You can use more specific property to get the value, instead of Request["word"], depends where the "word" key is:
In query string -> Request.QueryString["word"];
In ServerVariables -> Request.ServerVariables["word"];
In Params -> Request.Params["word"];
In Form -> Request.Form["word"];
In Cookies -> Request.Cookies["word"];
In Headers -> Request.Headers["word"];
In your case, you could use the 4th one: Request.Form["word"], but please make sure the <input> control is included in the BeginFrom tag.
Try binding a parameter to the form
[HttpPost]
public string GetWord([FromForm]string word)
{
var postedWord = word;
return postedWord;
}
As your form gets more complex you might like to create a class and bind the submitted form to that
public string GetWord([FromForm]MyFormModel formData)
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 ASP.NET MVC application which will work on a IIS7.
I don't know the final URL yet, and that's the problem.
I want to get the URL-Parts between the Top-level-domain and my controller.
For examople: http://www.mydomain.com/myApplication/MyController/ControllerMethodshould return /myApplication/MyController/
This should also be possible, if the application is called via the standard method, for example http://www.mydomain.com/myApplication.
The Problem is that with my method it works perfectly if the full controller- and methodname is in the url, but as soon as there is only the controller name and the route takes the default index-method or there is no controller/method and the route takes the default controller/method, it will fail because my code puts wrong output.
I thought about hardcoding the controller-name and make a if-then-else orgy, but this doesn't seem very professional...
Maybe anyone of you has got an Idea.
Here's my function:
String segments = Request.Url.Segments;
System.Text.StringBuilder builder = new System.Text.StringBuilder();
String lastSegment = "";
int i= 0;
do
{
builder.Append(segments[i]);
lastSegment = segments[i++];
} while(!lastSegment.Equals("Home") && !lastSegment.Equals("Home/") && i < segments.Length);
return builder.toString();
Use the Url class to build the Urls for you http://msdn.microsoft.com/en-us/library/system.web.mvc.urlhelper(v=vs.118).aspx
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.
Here is the code below
I tried this call but it didnt work... even if the function inside this call is empty i tried this exact function call with only 5 input parameters and it worked?
Something is fishy here hopefully someone can suggest and if you have anyway i can minimize this code meaning the parameters passes im open for suggestions anytime.
Code below:
[WebInvoke(UriTemplate = "customer/update/customerCode={customerCode}/customerName={customerName}/customerCountry={customerCountry}/customerTelephone={customerTelephone}/customerEmail={customerEmail}/customerCreditLimit={customerCreditLimit}/customerCommission={customerCommission}/customerRank={customerRank}/contactFullname={contactFullname}/contactBusinessPhone={contactBusinessPhone}/contactTimezone={contactTimezone}/contactActive={contactActive}/contactDepartment={contactDepartment}/contactHomePhoneExtension={contactHomePhoneExtension}/shipToCountry={shipToCountry}/shipToPaymentTerm={shipToPaymentTerm}/shipToCommissionPercent={shipToCommissionPercent}/shipToTruckSize={shipToTruckSize}/shipToTaxNumber={shipToTaxNumber}/shipToRouteCode={shipToRouteCode}/shipToOpenTime={shipToOpenTime}/shipToCloseTime={shipToCloseTime}", Method = "PUT", BodyStyle = WebMessageBodyStyle.Wrapped)]
public void UpdateCustomer(string customerCode, string customerName, string customerCountry, string customerTelephone, string customerEmail,
string customerCreditLimit, string customerCommission, string customerRank, string contactFullname,
string contactBusinessPhone, string contactTimezone, string contactActive, string contactDepartment,
string contactHomePhoneExtension, string shipToCountry, string shipToPaymentTerm, string shipToCommissionPercent,
string shipToTruckSize, string shipToTaxNumber, string shipToRouteCode, string shipToOpenTime,
string shipToCloseTime)
{
// code or no code
}
This is how I implement the function above:
using (HttpResponseMessage response = m_RestHttpClient.Put("customer/update/customerCode=CUST190/customerName=Ralph Lauren/customerCountry=United Kingdom/customerTelephone=1234567489/customerEmail=ralph#lauren.com/customerCreditLimit=1/customerCommission=5/customerRank=45/contactFullname=Diego Sin/contactBusinessPhone=911/contactTimezone=6/contactActive=True/contactDepartment=Sales/contactHomePhoneExtension=456/shipToCountry=Uganda/shipToPaymentTerm=NET30/shipToCommissionPercent=1/shipToTruckSize=50/shipToTaxNumber=777/shipToRouteCode=001/shipToOpenTime=10 am/shipToCloseTime=11pm", frm.CreateHttpContent()))
{
response.EnsureStatusIsSuccessful();
}
Thanks
You don't have a body parameter, PUT requires a body.
Beyond that, PUT is not equivalent to doing an Update stored procedure. Don't try and do this, it does not make any sense. All those parameters need to go in the body.
There are physical limits to URL length, so you may be running into an issue because of that.