How to pass array to php url from c#? [duplicate] - asp.net

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

Related

Redirect from one WebAPI to an another WebAPI and getting the response

I want to create lets say a master/core api.Want to check for a certain parameter value and redirect to a an external api hosted in the same server.I have an api with uri http://hello.test.com/auth which takes two auth params Username and Password.Now i add a third parameter lets say Area.
{
"Username":"jason",
"Password":"bourne",
"Area":"mars"
}
Now coming to the master api, if with this uri for example http://master.test.com/v1/mster and i pass Username, Password and Area,and if the Area has value of lets say "mars" it should call the external mars api having uri http://mars.test.com/auth ,do the auth the process and return the response in the master api.is this possible?
With my /auth api i have this controller returning the response :
[HttpPost]
[Route(ApiEndpoint.AUTH)]
public HttpResponseMessage Auth(Login authBDTO)
{
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState);
using (AccountBusinessService accountService = new AccountBusinessService())
{
var result = accountService.Auth(authBDTO);
return Request.CreateResponse(HttpStatusCode.OK, result);
}
}
Any Help Appreciated.Couldnt find this exact scenario in here.Sorry if too naive.
Found a workaround.This did the work.
[Route(ApiEndpoint.SAS)]
public IHttpActionResult esp(Login auth)
{
if (auth.Coop == "PMC")
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:60069/api/v1/auth");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
Username = auth.UserName,
Password = auth.Password
});
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(result);
obj.BaseUrl = "http://localhost:60069/api/v1";
return Ok(obj);
}
}

HttpPost method response with WebClient is null.

I know there are similar posts regarding calling an HttpPost method but nothing I've read/implemented has worked for me. I'm simply trying to do a POST call but the response is always null for some reason. I'm new to web development and ASP.
Here's my WebClient code:
using (WebClient webClient = new WebClient())
{
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var dataToSend = "=testingu";
var response = webClient.UploadString("http://localhost:5000/core/test", "POST", dataToSend);
Console.WriteLine("Response is: " + response);
}
and here's my HttpPost code:
[HttpPost("/core/test")]
public string PostObj([FromBody]dynamic input)
{
string result = "";
if (input == null)
System.Console.WriteLine("Input is null.");
else
System.Console.WriteLine("Input is not null: " + input);
return result;
}
Whenever PostObj is called, the "Input is null" line is always executed when I'm expecting to see "Input is not null: testingu" printed. It seems like my WebClient code is sound, but I'm pretty new to this so any help is appreciated.

REST WEBAPI POST method with parameters not being called

I have built a REST API with a controller having a POST method with 4 parameters like this-
[HttpPost]
public void SaveSession([FromBody] string userId, [FromBody] DateTime issueDateTime, [FromBody] string browserType, [FromBody] string salt)
{
// Params need to be changed
_sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}
How should I POST data on the client side, I mean what should be the format of the data to be sent?
I tried this format-
"userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
Its not working if I try this, The web service method is not even being called
Could anyone tell me the correct format?
EDIT:
Here is how I am calling the API-
const string endPoint = #"http://localhost:85/session/Test";
var postData = "userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
var request = (HttpWebRequest) WebRequest.Create(EndPoint + parameters);
request.Method = "POST";
request.ContentLength = 0;
request.ContentType = "application/x-www-form-urlencoded";
if (!string.IsNullOrEmpty(postData) && Method == HttpVerb.POST)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(postData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse) request.GetResponse())
{
var xmlDoc = new XmlDocument();
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
xmlDoc.Load(responseStream);
}
return (xmlDoc);
}
Thanks!
I assume routing has been properly configured.
Said so.... DateTime parameter in the controller method has been named "issueDateTime" while within the request has been named "DateTime".
I got to know, what mistake I was doing. I was sending 4 parameters in a WebService method. We can only send one parameter while calling a web service method. If you want to send multiple data, just send it as an object. Like this -
[HttpPost]
public void SaveSession([FromBody] Values value)
{
var userId = values.userId,
var issueDateTime= values.issueDateTime,
var browserType= values.browserType,
var salt= values.salt,
_sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}

Paypal Mass Payment API (Does Not Receive Response From paypal) with Asp.net using

I created MassPayment using MassPaymentAPI But I got Error In this Method
Input For Methods :::
url="https://api.sandbox.paypal.com/nvp"
postdata="METHOD=MassPay&EMAILSUBJECT=You+have+money!&RECEIVERTYPE=EmailAddress&CURRENCYCODE=USD&L_EMAIL0=bhaumik50%40gmail.com&L_Amt0=1.00&L_UNIQUEID0=&L_NOTE0=&USER=rserasiya_api1.gmail.com&PWD=OneIsTheLonliestNumber&VERSION=1&SOURCE=1" ;
timeout= "3600" ;
X509certificate = "Certifcate Description"
public static string HttpPost(string url, string postData, int timeout, X509Certificate x509)
{
HttpWebRequest objRequest = (HttpWebRequest) WebRequest.Create(url);
objRequest.Timeout = timeout;
objRequest.Method = "POST";
objRequest.ContentLength = postData.Length;
if (null != x509)
{
objRequest.ClientCertificates.Add(x509);
}
using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
{
myWriter.Write(postData);
}
using (WebResponse response = objRequest.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
}
In this method i succesfully sent request using StreamWriter object but i not got Response from paypal site so what should i do ? pls reply ..
my error is : The underlying connection was closed: The connection was closed unexpectedly.
I put image of my method which throws error and Browser Error.
pls give me your suggestion
The problem in your code is in Api url you are using
url="https://api.sandbox.paypal.com/nvp"
while you should use
url="https://api-3t.sandbox.paypal.com/nvp"

ASP.net: Getting HTTPS data server-side?

I previously asked on StackOverflow how to parse XML downloaded programmatically by my ASP.net application. By this, I mean that the user visits https://www.example.com/page1.aspx. The code-behind for page1.aspx is supposed to somehow download and parse an xml file located at https://www.example.com/foo.xml.
I received good answers about how to parse the XML. However, I've been out of luck with being able to retrieve XML from my secure HTTPS server.
I am looking at a situation where https://www.example.com/foo.xml authenticates requests with a cookie. (third party system, not Forms Authentication). The answer I received to my question about how to download and parse XML suggested that I use the System.Net.WebClient class. I read that the WebClient class must be customized to work with cookies. Therefore, I wrote the following code:
public class WebClientWithCookies : WebClient
{
private CookieContainer m_container = new CookieContainer();
public CookieContainer CookieContainer
{
get { return m_container; }
set { m_container = value; }
}
public void addCookie(Cookie cookie)
{
m_container.Add(cookie);
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if ( request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
} // end class
However, when the request is received at https://www.example.com/foo.xml, there are no cookies in the request, and so it doesn't work.
How can I work around this problem?
Where are you creating the cookie? That seems to be a missing part from the code you are displaying. There is an "HttpCookie" class as part of the System.Web name space that may be useful.
Here's the code that I eventually wrote that solved the problem:
private XmlDocument getXmlData(string url)
{
System.Net.HttpWebRequest rq = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
System.Net.CookieContainer container = new System.Net.CookieContainer();
for (int i = 0; i < System.Web.HttpContext.Current.Request.Cookies.Count; i++)
{
System.Web.HttpCookie httpcookie = System.Web.HttpContext.Current.Request.Cookies[i];
string name = httpcookie.Name;
string value = httpcookie.Value;
string path = httpcookie.Path;
string domain = "my.domain";
System.Net.Cookie cookie = new System.Net.Cookie(name, value, path, domain);
container.Add(cookie);
}
rq.CookieContainer = container;
rq.Timeout = 10000;
rq.UserAgent = "Asset Tracker Server Side Code";
System.Net.HttpWebResponse rs = (System.Net.HttpWebResponse)rq.GetResponse();
System.Text.Encoding enc = System.Text.Encoding.GetEncoding(1252);
System.IO.StreamReader reader = new System.IO.StreamReader(rs.GetResponseStream());
System.Xml.XmlDocument xml = new System.Xml.XmlDocument();
xml.Load(rs.GetResponseStream());
return xml;
}

Resources