Unauthorized (401) when calling one localhost website from another - asp.net

I have two websites set up on my local system running IIS 5.1 (on localhost). I am calling one website from another. I am working with ASP.NET, C# 2.0.
public static String executeWebRequest(string url, Boolean esmRequest)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
UTF8Encoding encoding = new UTF8Encoding();
Stream requestStream = null;
HttpWebResponse response = null;
StreamReader responseStream = null;
string responseString;
try
{
//post request
request.Method = "POST";
if (esmRequest)
{
//request.UseDefaultCredentials = true;
request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ESMServerUserName"], ConfigurationManager.AppSettings["ESMServerPassword"]);
}
else
{
//request.UseDefaultCredentials = true;
request.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ESMServerUserName"], ConfigurationManager.AppSettings["ESMServerPassword"]);
}
requestStream = request.GetRequestStream();
requestStream.Write(new byte[0], 0, 0);
requestStream.Close();
//get response
response = (HttpWebResponse)request.GetResponse();
responseStream = new StreamReader(response.GetResponseStream(), encoding);
responseString = responseStream.ReadToEnd();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (requestStream != null)
{
requestStream.Close();
}
if (response != null)
{
response.Close();
}
if (responseStream != null)
{
responseStream.Close();
}
}
return responseString;
}
}
I run this code and get a 401 HTTP status code. 1 errorm whereas when I paste the same URL in the browser it executes perfectly.
I already have DisableLoopbackCheck enabled using http://support.microsoft.com/kb/89686/en-us
How can I resolve this?

I was able to fix it with this change
var cache = new CredentialCache();
NetworkCredential credential = new NetworkCredential(ConfigurationManager.AppSettings["ESMServerUserName"], ConfigurationManager.AppSettings["ESMServerPassword"]);
cache.Add(new Uri(url), "Basic", credential);
request.Credentials = cache;

Related

how to call google acknowledge api from wcf service?

i need to add a call to google acknowledge endpoint into existing dotnet web service app.
this is the refence page https://developers.google.com/android-publisher/api-ref/rest/v3/purchases.products/acknowledge
i never worked on this app before, and i can not ask who developed it, He went away.
in the web.config are stored PlayStore ClientId and ClientSecret.
this is existing and working call to check a subscription:
internal PlayStoreSubscriptionPurchaseStatus verifySubscription(string packageName, string subscriptionId, string token, ref long timeMills)
{
Stopwatch watcher = new Stopwatch();
string accessToken = this.generateNewAccessToken(ref timeMills);
string verifySubscriptionAddress = _playStoreApisAddress + packageName + "/purchases/subscriptions/" + subscriptionId + "/tokens/" + token + "?access_token=" + accessToken;
PlayStoreSubscriptionPurchaseStatus playStoreResponse = null;
try
{
HttpWebRequest verifyRequest = WebRequest.Create(verifySubscriptionAddress) as HttpWebRequest;
verifyRequest.Method = "GET";
verifyRequest.ContentType = "application/json; charset=utf-8";
verifyRequest.Accept = "application/json; charset=utf-8";
watcher.Start();
using (HttpWebResponse verifyResponse = verifyRequest.GetResponse() as HttpWebResponse)
{
watcher.Stop();
Stream responseStream = verifyResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseAsString = streamReader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
if (verifyResponse.StatusCode == HttpStatusCode.OK)
playStoreResponse = jss.Deserialize<PlayStoreSubscriptionPurchaseStatus>(responseAsString);
else
{
playStoreResponse = new PlayStoreSubscriptionPurchaseStatus() { Success = false, ErrorMessage = responseAsString };
}
}
}
catch (WebException webEx)
{
using (StreamReader streamReader = new StreamReader(webEx.Response.GetResponseStream()))
{
string webExResponse = streamReader.ReadToEnd();
throw new Exception("Errore nella verifica subscription google play.\nErrore restituito dalle api google play:\n" + webExResponse);
}
}
finally
{
if (watcher.IsRunning)
watcher.Stop();
timeMills += watcher.ElapsedMilliseconds;
}
return playStoreResponse;
}
this code generates access_token:
private string generateNewAccessToken(ref long timeMills)
{
Stopwatch watcher = new Stopwatch();
string newAccessToken = string.Empty;
string postDta = string.Format("grant_type={0}&client_id={1}&client_secret={2}&refresh_token={3}",
"refresh_token", Uri.EscapeDataString(_clientId), Uri.EscapeDataString(_clientSecret), Uri.EscapeDataString(_refreshToken));
try
{
HttpWebRequest refreshAccessTokenRequest = WebRequest.Create(_refreshTokenAddress) as HttpWebRequest;
refreshAccessTokenRequest.Method = "POST";
refreshAccessTokenRequest.ContentType = "application/x-www-form-urlencoded";
//refreshAccessTokenRequest.ContentLength = new UTF8Encoding().GetBytes(postDta).Length;
refreshAccessTokenRequest.Accept = "application/json; charset=utf-8";
Stream refreshTokenRequestStream = refreshAccessTokenRequest.GetRequestStream();
StreamWriter streamWriter = new StreamWriter(refreshTokenRequestStream);
streamWriter.Write(postDta);
streamWriter.Close();
watcher.Start();
using (HttpWebResponse refreshAccessTokenResponse = refreshAccessTokenRequest.GetResponse() as HttpWebResponse)
{
watcher.Stop();
Stream responseStream = refreshAccessTokenResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream);
string responseAsString = streamReader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
RenewAccessTokenResponse renewAccessTokenResponse = jss.Deserialize<RenewAccessTokenResponse>(responseAsString);
newAccessToken = renewAccessTokenResponse.access_token;
}
}
catch (WebException webEx)
{
using (StreamReader streamReader = new StreamReader(webEx.Response.GetResponseStream()))
{
string webExResponse = streamReader.ReadToEnd();
throw new Exception(webExResponse);
}
}
finally
{
if (watcher.IsRunning)
watcher.Stop();
timeMills += watcher.ElapsedMilliseconds;
}
return newAccessToken;
}
what i want to know is if i can, using only httpwebrequest, make a call to acknlowelage api,
access token generate from generateNewAccessToken is good for this api?
if yes where do i have to store it? acknlowelage is POST while all existing calls in the project are GET. do i have store the access code in body or into some header?
there is somewhere a working sample?
thanks.

Uploading image to folder in ASP.net and C#

I have tried various answers here on StackOverflow but, none have solved the problem. I am trying to upload an image via file type to a folder called Images. The problem is that it always hits the catch in the try/catch. I have the block of code below but, removed the credentials for security. Please help!
[HttpPost]
public ActionResult UploadPhoto(HttpPostedFileBase file)
{
string http = "https://serverName";
string httpFolder = "/Images";
byte[] fileBytes = null;
string fileName = Path.GetFileName(file.FileName);
using (StreamReader fileStream = new StreamReader(file.InputStream))
{
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd());
fileStream.Close();
}
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(http + httpFolder + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("username", "password");
request.ContentLength = fileBytes.Length;
request.UsePassive = true;
request.UseBinary = true;
request.ServicePoint.ConnectionLimit = fileBytes.Length;
request.EnableSsl = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(fileBytes, 0, fileBytes.Length);
requestStream.Close();
}
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
ViewBag.FileUploaded = "File uploaded succesfully!";
}
catch (WebException ex)
{
throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
}
return RedirectToAction("UploadPhoto");
}

Mendeley Pagination

There are currently 1205 resources (citations) in the SciTS Mendeley group. However, no matter how we call the “getDocuments” method of the API, we only get the first 1000 resources. Is there a specific parameter we need to pass to get the full list of resources? Or is there a way to make a subsequent call that gets data pages not returned by the first call?
string grantType = "client_credentials";
string applicationID = "id";
string clientsecret = "XXXXXXX";
string redirecturi = "*******";
string url = "https://api-oauth2.mendeley.com/oauth/token";
string view = "all";
string group_id = "f7c0e437-f68b-34df-83c7-2877147ba8f9";
HttpWebResponse response = null;
try
{
// Create the data to send
StringBuilder data = new StringBuilder();
data.Append("client_id=" + Uri.EscapeDataString(applicationID));
data.Append("&client_secret=" + Uri.EscapeDataString(clientsecret));
data.Append("&redirect_uri=" + Uri.EscapeDataString(redirecturi));
data.Append("&grant_type=" + Uri.EscapeDataString(grantType));
data.Append("&response_type=" + Uri.EscapeDataString("code"));
data.Append("&scope=" + Uri.EscapeDataString("all"));
byte[] byteArray = Encoding.UTF8.GetBytes(data.ToString());
// Setup the Request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
// Write data
Stream postStream = request.GetRequestStream();
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Send Request & Get Response
response = (HttpWebResponse)request.GetResponse();
string accessToken;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the Response Stream
string json = reader.ReadLine();
Console.WriteLine(json);
// Retrieve and Return the Access Token
JavaScriptSerializer ser = new JavaScriptSerializer();
Dictionary<string, object> x = (Dictionary<string, object>)ser.DeserializeObject(json);
accessToken = x["access_token"].ToString();
}
// Console.WriteLine("Access TOken"+ accessToken);
var apiUrl = "https://api-oauth2.mendeley.com/oapi/documents/groups/3556001/docs/?details=true&items=1250";
try
{
request = (HttpWebRequest)WebRequest.Create(apiUrl);
request.Method = "GET";
request.Headers.Add("Authorization", "Bearer " + accessToken);
request.Host = "api-oauth2.mendeley.com";
response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
// Get the Response Stream
string json = reader.ReadLine();
Console.WriteLine(json);
//need this to import documents
}
}
catch (WebException ex1)
{
Console.WriteLine("Access TOken exception" + ex1.Message);
}
}
catch (WebException e)
{
if (e.Response != null)
{
using (HttpWebResponse err = (HttpWebResponse)e.Response)
{
Console.WriteLine("The server returned '{0}' with the status code '{1} ({2:d})'.",
err.StatusDescription, err.StatusCode, err.StatusCode);
}
}
}
The default number of items returned is limited to 1000 per page. For a paginated response you should get some additional fields in the response; notably 'items_per_page','total_pages','total_results'.
I suspect you have will two pages and to get the next result you need to append 'page=1'.

The remote server returned an error: (400) Bad Request. When try to login with facebook in asp.net

I am try to login with a user with Facebook account in my website, but the applcation gives me error that The remote server returned an error: (400) Bad Request.
Below is my code:
public string WebRequest(Method method, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = "[You user agent]";
webRequest.Timeout = 50000;
if (method == Method.POST)
{
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
*It gives me error in this method:*
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
Ooo been a while since Iv'e played with webRequest but I think your problem might be
webRequest.GetResponse().GetResponseStream().Close();
in the finally block. Since you've already called
webRequest.GetResponse().GetResponseStream()
in the body of try block. Documentation states:
The GetResponse method sends a request to an Internet resource and
returns a WebResponse instance. If the request has already been
initiated by a call to GetRequestStream, the GetResponse method
completes the request and returns any response.
Therefore as I read it, the response had already been returned in the try block and then when you call it again in the finally block, it fails...since it's already been retrieved. Just comment out that line and see how you go. The StreamReader should close the underlying connection when you close it.
So try:
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
responseReader.Close();
}
return responseData;
}

Request a page with server code

I need to request a series of pages and want to do from the server code as if you were doing with Ajax, I can do?, thanks
You're looking for the WebClient class.
Use this c# function. Add using System.Net; top of your page.
private string MakeWebRequest(string url) {
string retValue = String.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = null;
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse();
StreamReader stReader = new StreamReader(response.GetResponseStream());
retValue = stReader.ReadToEnd();
stReader.Close();
response.Close();
stReader.Dispose();
stReader = null;
response = null;
request = null;
}
catch (Exception ex) {
}
return retValue;
}

Resources