I'm doing a simple page to upload document. However after I get the input I need to call a web API to get a token which will then allow me to call another web API which will finally proceed to upload the file (using the file AND the token). So what I want to know is how to call this API and retrieve it's response and then add that response (which would be the token).
I am trying following code it works fine in console application but not work on web Application.
here is my code
public void GetTokenpost()
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
string url = "mydomain/api/oauth/token";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
string data = "grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=here jwt token"; // make sure this is URL encoded
request.ContentType = "application/json";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(data);
streamWriter.Flush();
streamWriter.Close();
var HttpResponse = (HttpWebResponse)request.GetResponse();
using (var streamRead = new StreamReader(HttpResponse.GetResponseStream()))
{
var value1 = streamRead.ReadToEnd();
Console.WriteLine("Hello {0}",
}
}
}
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://domain");
//Called Member default GET All records
//GetAsync to send a GET request
// PutAsync to send a PUT request
var responseTask = client.GetAsync(string requestUri);
responseTask.Wait();
//To store result of web api response.
var result = responseTask.Result;
//If success received
if (result.IsSuccessStatusCode)
{
//your code for performing action
}
Related
I want to redirect a system to a centralized authentication server and I need to fill some parameters in headers and redirect to the authentication server completely. Using Web Client or Web Request I must return a value as a response to the requester ( They work as a listener ).
WebClient Send Request Example:
var values = new NameValueCollection();
values["clientId"] = clientId;
values["clientIP"] = currentIP;
byte[] response;
var resultResponse = string.Empty;
using (var client = new WebClient())
{
try {
response = client.UploadValues(url, values);
resultResponse = Encoding.Default.GetString(response);
}
catch (WebException e)
{
string exception = string.Empty;
if (e.Status == WebExceptionStatus.ProtocolError)
{
exception += ((HttpWebResponse)e.Response).StatusCode;
exception += ((HttpWebResponse)e.Response).StatusDescription;
}
}
}
Web Request Example
string method = "post";
WebRequest req = WebRequest.Create(uri);
req.ContentType = contentType;
req.Method = method;
req.Headers.Add("myhead", value);
req.ContentLength = jsonDataBytes.Length;
var stream = req.GetRequestStream();
stream.Write(jsonDataBytes, 0, jsonDataBytes.Length);
stream.Close();
var response = req.GetResponse().GetResponseStream();
StreamReader reader = new StreamReader(response);
var respo = reader.ReadToEnd();
reader.Close();
response.Close();
return respo;
As you see in both methods the requester post the request and is waiting till receiving the response. I can not return to the requester system until I show two view to the user, get the username and passwords and finally process the information. I need to fill headers in a request, post it to the server and also redirect to the central authentication server. I searched a lot and found that it is impossible to post and redirect at a same time. Can you suggest any other methods to me?
I am looking to modify the Firebase realtime database from my web-app using an HTTP post request.
I have written the post request, but it seems to return a 405 error. Any good way around this?
Code below
var httpWebRequest = (HttpWebRequest)WebRequest.Create("*DatabaseURL*");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json2 = "{\"user\":\"test\"," +
"\"password\":\"bla\"}";
streamWriter.Write(json2);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
Ended up using a custom SDK called FirebaseDatabase. Found here.
https://github.com/step-up-labs/firebase-database-dotnet
Here is the code that I am using:
public static void FetchXML()
{
_url = new Uri("http://api.tumblr.com/v2/blog/" + _username + ".tumblr.com/likes?api_key=REc3Z6l4ZYss11a8lX6KKje0X8Hsi9U77SyaPbQrOBBCGJGA6D");
var client = new RestClient();
client.Authority = _url.ToString();
var request = new RestRequest();
request.AddParameter("limit", "20");
request.AddParameter("offset", _offset.ToString());
var response = client.Request(request);
var content = response.Content.ToString();
var parsedResponse = JsonParser.FromJson(content);
}
If I take the Uri value and paste it into my browser (using a valid Tumblr username) I'm getting the correct Json, but in my application the content of response is:
"{\"meta\":{\"status\":401,\"msg\":\"Unauthorized\"},\"response\":[]}"
Anyone have any idea why this is? According to the Tumblr API
retrieving likes should only need the API key, which I am providing.
Hi you can use the below code to get the response.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "Application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receive = response.GetResponseStream();
StreamReader reader = new StreamReader(receive, Encoding.UTF8);
string respond = reader.ReadToEnd();
I'm adding twitter integration to my companies web application but I'm hitting a snag on it.
The issue currently is with the callback url.
In twitter it seems that it wants to have a set value but the way our application is setup, each customer that access the site has their own url.
ideally I'd like to set the callback url on the fly, but I'm having a hard time finding any information on that.
EDIT:
Think I may need to add some more details here to better help you help me
The issue is I setup the callback url parameter to https://api.twitter.com/oauth/request_token but when I go to https://api.twitter.com/oauth/authorize to get permission, it will go to the callback setup on the api, not what I set from the previous request.
here is what my code looks like:
public string oAuthToken(string callbackUrl)
{
Uri oauthUrl = new Uri("https://api.twitter.com/oauth/request_token");
var oauthNonce = Convert.ToBase64String(new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var oauthTimestamp = this.GenerateTimeStamp();
var oauthSignature = "";
var authSignature = string.Format("oauth_callback=\"{0}\"&oauth_consumer_key=\"{1}\"&oauth_nonce=\"{2}\"&oauth_signature_method=\"{3}\"&oauth_timestamp=\"{4}\"&oauth_version=\"{5}\"",
Uri.EscapeDataString(callbackUrl),
Uri.EscapeDataString(this.ConsumerKey),
Uri.EscapeDataString(oauthNonce),
Uri.EscapeDataString(oauthSignatureMethod),
Uri.EscapeDataString(oauthTimestamp),
Uri.EscapeDataString(oauthVersion));
var baseString = string.Format("POST&{0}&{1}", Uri.EscapeDataString(oauthUrl.AbsoluteUri), Uri.EscapeDataString(authSignature));
var compositeKey = string.Concat(Uri.EscapeDataString(this.ConsumerSecret), "&");
using (HMACSHA1 hasher = new HMACSHA1(Encoding.ASCII.GetBytes(compositeKey)))
{
oauthSignature = Convert.ToBase64String(hasher.ComputeHash(Encoding.ASCII.GetBytes(baseString)));
}
var authHeader = string.Format("oauth oauth_callback=\"{0}\", oauth_consumer_key=\"{1}\", oauth_nonce=\"{2}\", oauth_signature=\"{3}\", oauth_signature_method=\"{4}\", oauth_timestamp=\"{5}\", oauth_version=\"{6}\"",
Uri.EscapeDataString(callbackUrl),
Uri.EscapeDataString(this.ConsumerKey),
Uri.EscapeDataString(oauthNonce),
Uri.EscapeDataString(oauthSignature),
Uri.EscapeDataString(oauthSignatureMethod),
Uri.EscapeDataString(oauthTimestamp),
Uri.EscapeDataString(oauthVersion));
ServicePointManager.Expect100Continue = false;
HttpWebRequest authRequest = (HttpWebRequest)System.Net.WebRequest.Create(oauthUrl);
authRequest.Method = "POST";
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Headers.Add("Accept-Encoding", "gzip");
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
try
{
using (var response = authRequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
}
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
return sr.ReadToEnd();
}
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
}
I always get a 401 error back.
While in the application set-up at https://apps.twitter.com/ a callback URL is required, the OAuth 1.0A spec mandates that a callback URL be passed with the request token. You can pass any valid URL to with that request, effectively having each of your callbacks go to the unique URL for each of your users. So, you're not locked into the callback URL in your application's set-up.
I have 2 c# asp.net projects. 1 is an api. 1 is consuming this api.
My api:
public class MyApiController : ApiController
{
public dynamic ValidateToken(string token)
{
return myValidationMethod(token);
}
}
Consuming my api from another project:
public class MyController : Controller
{
[HttpPost]
public ActionResult ValidateToken(string token)
{
var url = "http://localhost:1234/myapi/validatetoken";
var parameters = "token=" + token;
using (var client = new WebClient())
{
var result = client.UploadString(url, parameters);
return Json(result);
}
}
}
In project 2 where I consume the api, client.UploadString throws a System.Net.WebException - The remote server returned an error: (404) Not Found.
When I test the api with the chrome rest client it works with http://localhost:1234/myapi/validatetoken?token=myToken
Why can WebClient not find it?
Solved
I got this to work thanks to #BrentMannering with a small change to add content length:
var url = "http://localhost:1234/myapi/validatetoken?token=" + token;
var request = WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = 0; //got an error without this line
var response = request.GetResponse();
var data = response.GetResponseStream();
string result;
using (var sr = new StreamReader(data))
{
result = sr.ReadToEnd();
}
return Json(result);
I don't think UploadString is sending the data as params, so the routing engine on the API side cannot map to an action, hence the 404. According to the MSDN documentation the method is encoding to a Byte[] prior to uploading, this could be part of the problem.
Try using the UploadValues method
var url = "http://localhost:1234/myapi/validatetoken";
var nv = new NameValueCollection { { "token", token } };
using (var client = new WebClient())
{
var result = client.UploadValues(url, nv);
return Json(result);
}
Otherwise to mimic the test you are doing with the chrome client use WebRequest
var url = "http://localhost:1234/myapi/validatetoken?token=" + token;
var request = WebRequest.Create(url);
request.Method = "POST";
var data = request.GetResponse().GetResponseStream();
string result = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
result = sr.ReadToEnd();
}
return Json(result);
WebClient.UploadString method sends an Http POST method. Did you try to access your APIController with a POST method from the test client ? I am assuming your test client sent a GET request and it worked.
There is a different overload where you can mention the Action method type.
var url = "http://localhost:1234/myapi/validatetoken";
var parameters = "token=" + token;
string method = "GET"; //or POST as needed
using (var client = new WebClient())
{
var result = client.UploadString(url,method , parameters);
return Json(result);
}