Error :The remote server returned an error: (401) Unauthorized - asp.net

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

Related

You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse

I tried to upload file on oracle cloud infrastructure iaas but getting the error.I am not sure whether the file that I attached in the body is in
correct format or not. ApI signing is correct and I am doubt only about
whether the code that I wrote is upto mark or not. The code snippet is mentioned below.
The code Snippet :
FileInfo f = new FileInfo(FileUpload1.FileName);
byte[] filebyte =FileUpload1.FileBytes;
var postdata = Encoding.UTF8.GetBytes(filebyte.ToString());
Console.Write(postdata.Length);
var tenancyId = ConfigurationManager.AppSettings["BMCTenancyId"];
var userId = ConfigurationManager.AppSettings["BMCUserId"];
var fingerprint = ConfigurationManager.AppSettings["BMCFingerprint"];
var privateKeyPath = ConfigurationManager.AppSettings["BMCPrivateKeyPath"];
var privateKeyPassphrase = ConfigurationManager.AppSettings["BMCPrivateKeyPassphrase"];
var signer = new RequestSigner(tenancyId, userId, fingerprint, privateKeyPath, privateKeyPassphrase);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/");
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/json";
request.SendChunked = true;
request.ContentType = "text/plain";
request.ContentLength =postdata.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(postdata, 0, postdata.Length);
stream.Close();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
request.Headers["x-content-sha256"] = Convert.ToBase64String(SHA256.Create().ComputeHash(postdata));
signer.SignRequest(request);
Console.WriteLine($"Authorization header: {request.Headers["authorization"]}");
ExecuteRequest(request);
Console.WriteLine("The value of 'ContentLength' property after sending the data is {0}", request.ContentLength);
}
private static void ExecuteRequest(HttpWebRequest request)
{
try
{
var webResponse = (HttpWebResponse)request.GetResponse();
var response = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
Console.WriteLine($"Response: {response}");
}
catch (WebException e)
{
Console.WriteLine($"Exception occurred: {e.Message}");
Console.WriteLine($"Response: {new StreamReader(e.Response.GetResponseStream()).ReadToEnd()}");
}
}
For one thing, you'll need to update the URL to the following format:
var uri = new Uri($"https://objectstorage.us-phoenix-1.oraclecloud.com/n/{namespaceName}/b/{bucketName}/o/{objectName}");
Docs: https://docs.cloud.oracle.com/iaas/api/#/en/objectstorage/20160918/Object/PutObject
Also, can you please edit the question to include the complete error you are receiving, that will help with debugging.

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?

How can I use auth cookie in cookie Aware Client to access secured web page?

Initially I'm login in to a secured webpage,then m getting the cookie manually and then i have to set the cookie while making another call to fetch data from authorized web url.
how can I make one cookie aware client which do not require to set the auth cookie again and again. it should automatically set the auth cookie and get the required data.
My code is
CPSession retVal = null;
if (guid != "")
retVal = TokenManager.getSessionInfo(guid);
ServicePointManager.ServerCertificateValidationCallback = delegate
{ return true; };
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create(address);
httpWReq.CookieContainer = new CookieContainer();
Encoding encoding = new UTF8Encoding();
byte[] bdata = encoding.GetBytes(postData);
httpWReq.ProtocolVersion = HttpVersion.Version11;
httpWReq.Method = "PUT";
httpWReq.ContentType = "application/json; charset=utf-8";
httpWReq.CookieContainer.SetCookies(new Uri(address), retVal.getAttributeValue(CookieType)); // here I'm setting cookie manually.
httpWReq.ContentLength = bdata.Length;
Stream stream = httpWReq.GetRequestStream();
stream.Write(bdata, 0, bdata.Length);
stream.Close();
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string s = response.ToString();
StreamReader reader = new StreamReader(response.GetResponseStream());
You can create one cookie aware client like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace SunPowerService.Service
{
public class CookieAwareWebClient : WebClient
{
public CookieContainer m_container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = m_container;
}
return request;
}
}
}
and you can call it like this
using (var client = new CookieAwareWebClient())
{
Uri uri = new Uri("YourUrlToGetAuthCookie");
client.m_container.SetCookies(uri, strCookieVal);
jsonresponse = client.DownloadString(uri);
}

How to release the resource of the used HttpRequest and HttpRespone

All, Usually if we want to release the resource of something like Connection or Stream. we have to call the method like close() to make that in Asp.net.
But I don't find any method of HttpWebRequest like close() to let Asp.Net to release the resource.
So, Commonly if I want to use HttpWebRequest or HttpWebResponse , the code snippet kind like this way . Please review below. Is there anything wrong with it ? I am not sure about that . Thanks.
try
{
HttpWebRequest request = createGetHttpRequest(detailModel, RequestServiceType.GetToken,null);
string returnedContent = string.Empty;
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
returnedContent = reader.ReadToEnd();
reader.Close();
}
}
// string statusCode = response.StatusCode.ToString();
response.Close();
}
}
catch (Exception e)
{
Log.Write(e);
}

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