Request a page with server code - asp.net

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;
}

Related

Created a Soap Webservice and calling it in asp.net uisng code and getting error of The remote name could not be resolved

I had developed one web service in SOAP format and trying to access service in asp.net using the below mentioned code.
public static void CallWebService()
{
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _url = "https://test.in/ModelDetail/Service.asmx";
var _action = "https://test.in/ModelDetail/GetWarrantyDetails";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
//using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (HttpWebResponse webResponse= (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch(Exception ex) { throw ex; }
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='https://ndb.bmw.in/'><soapenv:Header/><soapenv:Body><tem:GetWarrantyDetails><tem:IP><demono>WBA3Y37070D45</demono></tem:IP></tem:GetWarrantyDetails></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
but when i call this code i get error of The remote name could not be resolved.
Tried all method but get this error only.
What is missing or wrong i am doing?

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;
}

Web API Login with Cookie

I have an ASP.Net Web API and the documentation states I need to save an Auth Token to a cookie then pass it back for API requests. I can get the Auth Token without a problem. My question is what is the best way to save the cookie and send it back in the request.
I create a cookie in the RequestMessage, but I cannot find a way to send it back when making a request against the API. How do I preserve the state of the Login/cookie.
Any help is greatly appreciated, thanks.
Update
I am now able to obtain the cookie from the response. I am using this tutorial. http://www.asp.net/web-api/overview/working-with-http/http-cookies Let me point out if you want to use this tutorial make sure you update the Web API 4's code base. In the below method i am trying to simply, Login and Logout. However, I am receiving an Error Code 500.
public HttpWebResponse InitializeWebRequest()
{
//HttpResponseMessage logoutMessage = await Logout("bla");
string responseData = string.Empty;
string url = GetServerEndPoint();
string authToken = string.Empty;
string loginInstance = "https://example.com";
// Create request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
IList<string> authHeader = responseData.Split('{', '}').ToList();
authToken = authHeader[2].Substring(13, 25);
string sessionId = response.Headers.Get(8);
var nv = new NameValueCollection();
nv["sid"] = sessionId;
nv["token"] = authToken;
CookieHeaderValue cookieVal = new CookieHeaderValue("session", nv);
// Log out
string loginInstance2 = "https://example.com";
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(loginInstance2);
request2.Method = "POST";
request2.ContentType = "application/json";
request2.Headers.Add(nv);
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponseAsync().Result;
}
return response;
}
WOW WHAT A PAIN!
I have no idea why this took me so long to figure out, but after hours and hours and DAYs, of trying to get this stupid auth to work I finally figured it out. Here is the code.
One weird thing is I had to create the header format for the cookie. Which by definition isn't a true cookie, it is a damn header value. I had to create the header title, because when I extracted the JSON object from the file and converted it to string I was unable to keep the format in tact from the file.
public HttpWebResponse InitiliazeWebRequest()
{
string responseData = string.Empty;
string loginInstance = "url + logincreds";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "POST";
request.ContentType = "application/json";
request.CookieContainer = new CookieContainer();
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
var toke = response.Headers.Get("authToken");
JObject o = JObject.Parse(responseData);
_authToken = (string)o["response"]["authToken"].ToString();
return response;
}
return response;
}
public HttpWebResponse LogOut()
{
string responseData = string.Empty;
string loginInstance = "https://www.example.com/logout";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Cookie: authToken=" + _authToken);
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
if (response.StatusCode == HttpStatusCode.OK)
{
using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
return response;
}
return response;
}

Unauthorized (401) when calling one localhost website from another

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;

Error :The remote server returned an error: (401) Unauthorized

I want get picture of internet and insert into word .
I use this code .
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
System.Net.WebRequest request =
System.Net.HttpWebRequest.Create("http://spsdev2:1009");
System.Net.WebResponse response = request.GetResponse();
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
//Send an HTTP request and get the image at the URL as an HTTP response
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(fileName);
WebResponse myResp = myReq.GetResponse();
//Get a stream from the webresponse
Stream stream = myResp.GetResponseStream();
I get error in myReq.GetResponse();
Error :The remote server returned an error: (401) Unauthorized.
Edit
This code work for me :)
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
I add credentials for HttpWebRequest.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?
Something like request.Credentials = new NetworkCredential("UserName", "PassWord");
Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}

Resources