Get raw querystring of WebClient in C# - c#

I'm using a WebClient to make a POST request with a query string but I can't see the raw string. This is what I have:
WebClient TheWebClient = new WebClient();
TheWebClient.QueryString.Add("Param1", "1234");
TheWebClient.QueryString.Add("Param2", "4567");
TheWebClient.QueryString.Add("Param3", "4539");
var TheResponse = TheWebClient.UploadValues("https://www.example.com/posturl", "POST", TheWebClient.QueryString);
string TheResponseString = TheWebClient.Encoding.GetString(TheResponse);
//problem is that this only shows the keys
var RawQueryString = TheWebClient.QueryString;
How can I see the actual raw query string?

WebClient.UploadValues doesn't save the request "raw query string" simply because you provided it with them, and it's not gonna change, thus is redundant.
Furthermore, HttpPost requests doesn't use query string for the request payload, it has a url, a message payload; which is appended after the headers, maybe query string. Thus there is nothing new the client class should let you know, so it won't save it.

Related

How to send multiple parameters to a Web API call using WebClient

I want to send via POST request two parameters to a Web API service. I am currently receiving 404 not found when I try in the following way, as from msdn:
public static void PostString (string address)
{
string data = "param1 = 5 param2 = " + json;
string method = "POST";
WebClient client = new WebClient ();
string reply = client.UploadString (address, method, data);
Console.WriteLine (reply);
}
where json is a json representation of an object. This did not worked, I have tried with query parameters as in this post but the same 404 not found was returned.
Can somebody provide me an example of WebClient which sends two parameters to a POST request?
Note: I am trying to avoid wrapping both parameters in the same class only to send to the service (as I found the suggestion here)
I would suggest sending your parameters as a NameValueCollection.
Your code would look something like this when sending the parameters with a NameValueCollection:
using(WebClient client = new WebClient())
{
NameValueCollection requestParameters = new NameValueCollection();
requestParameters.Add("param1", "5");
requestParameters.Add("param2", json);
byte[] response = client.UploadValues("your url here", requestParameters);
string responseBody = Encoding.UTF8.GetString(response);
}
Using UploadValues will make it easier for you, since the framework will construct the body of the request and you won't have to worry about concatenating parameters or escaping characters.
I have managed to send both a json object and a simple value parameter by sending the simple parameter in the address link and the json as body data:
public static void PostString (string address)
{
string method = "POST";
WebClient client = new WebClient ();
string reply = client.UploadString (address + param1, method, json);
Console.WriteLine (reply);
}
Where address needs to expect the value parameter.

Send JSON list via GET Request

I am attempting to speed up the process of my local software sync. Right now we send a GET requested for each individual record that we need and the API sends back a JSON string containing that records data, which is then inserted into the local database. This all works, however it can be tediously slow. I am trying to speed this up, and was hoping a good way to do so would be to send a JSON of List<Dictionary<string, string>>. This would make it so that I can request much more data in one shot on the API side, add it to the list, and pass it back as JSON to the local machine.
Right now on the local side I have:
Encoding enc = System.Text.Encoding.GetEncoding(1252);
using (HttpClient client = new HttpClient())
{
string basicAuth = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", usr, pwd)));
client.BaseAddress = new Uri(baseUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", basicAuth);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string requested = JsonConvert.SerializeObject(tableList);
HttpResponseMessage response = client.GetAsync(syncUrl + hash + "/" + requested).Result;
if (!response.IsSuccessStatusCode)
{
// get the error
StreamReader errorStream = new StreamReader(response.Content.ReadAsStreamAsync().Result, enc);
throw new Exception(errorStream.ReadToEnd());
}
}
My Controller call looks like this:
[System.Web.Http.AcceptVerbs("GET")]
[Route("getRecords/{hash}/{requested}")]
public HttpResponseMessage getRecords(string hash, string requested)
Whenever I make this call it gives me an error that it cannot find the URI and I don't even hit my breakpoint on my API. How do I get this to work, or is there a better way to accomplish what I'm doing?
You need to urlencode the data, if there is any special url chars (like ampersand or slash) it will render unusable the data, so you must urlencode it to be rightly formatted.
Use something like...
string requested = Uri.EscapeDataString(JsonConvert.SerializeObject(tableList));
This will encode the special chars so them can be transferred securely on the URL.

Accessing query string variables sent as POST in HttpActionContext

I'm trying to access a query string parameter that was sent using the POST method (WebClient) to the Web API in ASP.NET MVC 5 (in an overridden AuthorizationFilterAttribute).
For Get, I've used the following trick:
var param= actionContext.Request.GetQueryNameValuePairs().SingleOrDefault(x => x.Key.Equals("param")).Value;
However, once I use POST, this does work and the variable paran is set to null. I think that's because the query string method only applies to the url, not the body. Is there any way to get the query string (using one method preferably) for both GET and POST requests?
EDIT: WebClient Code
using (WebClient client = new WebClient())
{
NameValueCollection reqparm = new NameValueCollection();
reqparm.Add("param", param);
byte[] responsebytes = client.UploadValues("https://localhost:44300/api/method/", "POST", reqparm);
string responsebody = Encoding.UTF8.GetString(responsebytes);
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responsebody);
}
}
Using the code you show, you upload the param=value in the request body using the application/x-www-form-urlencoded content-type.
If you also want to utilize the query string, you need to set it separately using the WebClient.QueryString property:
// Query string parameters
NameValueCollection queryStringParameters = new NameValueCollection();
queryStringParameters.Add("someOtherParam", "foo");
client.QueryString = queryStringParameters;
// Request body parameters
NameValueCollection requestParameters = new NameValueCollection();
requestParameters.Add("param", param);
client.UploadValues(uri, method, requestParameters);
This will make the request go to uri?someOtherParam=foo, enabling you to read the query string parameters serverside through actionContext.Request.GetQueryNameValuePairs().

Post method for HTTP Handler

I have a handler. When I call it with URL that is to say GET method, it works because I get values with my below handler code.
var encodedUrl = HttpUtility.UrlEncode(context.Request.QueryString.ToString());
How can I get values when I use post method which is below from Handler side:
using (var wb = new WebClient())
{
var data = new NameValueCollection();
data["a"] = "a";
data["b"] = "b";
var response = wb.UploadValues("http://localhost:126/Web", "POST", data);
}
When you receive an http response you basically depend on the "Content Type". Depending on this type is that you read it.
Here is a reference on this topic:
http://msdn.microsoft.com/en-us/library/ms525208(v=vs.90).aspx
For instance if you decide to receive an "application/json" response type. You may be able to use this:
Using WebClient for JSON Serialization?
From I can see in your sample it looks like you are trying to implement an "application/x-www-form-urlencoded" and the post needs to be formatted accordingly. Here is a sample for that:
http://msdn.microsoft.com/en-us/library/system.net.webclient.headers(v=vs.110).aspx
How are parameters sent in an HTTP POST request?
But there are other options available. I hope this is the answer you were looking for.

HTTP POST with JSON object returned c#

I am trying to create a HTTP Post that returns a JSON object with 2 attributes.
Details are below:
HTTP POST to http://text-processing.com/api/sentiment/ with form encoded data which contains a string. A JSON object response with 2 attributes is retuned; lable and negative.
I am tying to do this in c#, which is where I am struggling.
Thank you
You can try using a WebClient like this
WebClient webclient = new WebClient();
NameValueCollection postValues = new NameValueCollection();
postValues.Add("foo", "fooValue");
postValues.Add("bar", "barValue");
byte[] responseArray = webclient.UploadValues(*url*, postValues);
string returnValue = Encoding.ASCII.GetString(responseArray);
MSDN page also has an example.

Categories

Resources