How to use sended post data on server side - c#

I have a simple script to upload a file. Actually everything is working fine.
private void UploadCSV()
{
Uri address = new Uri("https://www.mydomain.xy/inc.upload.php");
string fileName = #"C:\test.csv";
using (WebClient client = new WebClient())
{
var parameters = new NameValueCollection();
parameters.Add("test", "aaaa");
client.QueryString = parameters;
client.UploadProgressChanged += WebClientUploadProgressChanged;
client.UploadFileCompleted += WebClientUploadCompleted;
client.UploadFileAsync(address, "POST", fileName);
}
}
Now as you can see, I try so send some data via POST test what contains aaaa. But now matter how I try to select the data serverside... there is nothing....
I tried $_POST['test'], $_POST['data']['test'].... but no results.
How can I access the extra Data ?

client.QueryString = parameters;
This will append a query string to the URL that you send the data to.
Even though the request method is POST, PHP always provides the query string parameters in $_GET.

Related

Sending a string from C# to insert into a PHP file to be immediately used in a mysql select query with the results returned

So I have this php file with the following query
$query = "select Customer.CustID, LastName,FirstName,DOB,CustPhone,
Max(TransDate) as LatestTransaction from Customer, History where
Customer.AuthKey='A111' and Customer.AuthKey=History.AuthKey and
Customer.CustID=History.CustID Group by CustID;";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
And then I do this C# here to get the results and put them into a datagridview
WebClient wc = new WebClient();
var json = wc.DownloadString(URL);
List<Customer> customers =
JsonConvert.DeserializeObject<List<Customer>>(json);
CustomerDataViewGrid.DataSource = customers;
There are no problems with this, however I would like to take
Customer.AuthKey = 'A111'
From the above select query in the php And instead pass the value from my C# code to it
$aKey = $_POST['Authkey'];
Customer.AuthKey = '$aKey'
I have tried to do this within the same button click event but I am not quite understanding how I can send this string and then immediately get the Downloading string. When I hard code the Customer.Authkey it returns my results, but when I try to send this string it does not return anything. How can I do this from the same event?
Thanks
NameValueCollection formData = new NameValueCollection() {
{ "Authkey", "A111" },
};
byte[] result = wc.UploadValuesTask("<your_url_here>", "POST", formData);
string json = Encoding.UTF8.GetString(result);
By this was you can send your auth key to your PHP script. The rest is up to you. Sorry if I misunderstood you, feel free to correct me.

Get raw querystring of WebClient in 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.

PHP to C# variables

I have the following PHPcode:
include 'db.php';
$user = $_POST['username'];
$q = $connection->query('SELECT id FROM myTable WHERE username=".$user."');
foreach($q AS $row) {
echo $row['id'];
}
I'm trying to make a C# application post a variable to a PHP page that then queries the db and echos a string that will be used in the C# app. My C# code looks like this:
public string getId(string url)
{
string test = "testing123";
NameValueCollection formData = new NameValueCollection();
formData["username"] = test;
using (WebClient wc = new WebClient())
{
byte[] resp = wc.UploadValues(url, "POST", formData);
string responsefromserver = Encoding.UTF8.GetString(resp);
wc.Dispose();
Console.WriteLine(responsefromserver);
return responsefromserver;
}
}
As you can see, I just want to write what the app gets back from the PHP page to the console and then return it, but when I run the app, it returns nothing. At least it appears to. Does anyone have any idea why? Sorry if this is blatantly obvious, I'm still pretty new to the whole C# thing.
replace
$q = $connection->query('SELECT id FROM myTable WHERE username=".$user."');
with
$q = $connection->query('SELECT id FROM myTable WHERE username='.$user.';');
and try again.
As a best practise, use prepared statement to avoid SQL injection.

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.

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().

Categories

Resources