How to send authorized request - asp.net

I send programatically a request to remote server:
string xml = "SomeXML Data";
string url = #"http://someserver.com";
WebRequest request = WebRequest.Create(url);
request.Method = "Post";
request.ContentType = "text/xml";
//The encoding might have to be chaged based on requirement
UTF8Encoding encoder = new UTF8Encoding();
byte[] data = encoder.GetBytes(xml); //postbody is plain string of xml
request.ContentLength = data.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
System.Net.WebResponse response = request.GetResponse();
System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
but this code throws error:
The remote server returned an error: (401) Unauthorized.
I know user/pass to autorize when IE ask me.
Could anyone help me how to send authorized request?
Thanks!

webClient.Credentials = new NetworkCredential("Login", "Password");

Server seems to use Windows Authentication - although I am only guessing. If it is so, add this line:
request.Credentials = CredentialCache.DefaultCredentials;

looks like the server is using windows integrated security?
try something like this
WebRequest req = WebRequest.Create(tokenUri);
req.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;
req.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;

Related

Forward a QueryString to another Server

I have a webapp that accepts a messageid and status as a QueryString from an external server. I am migrating the webapp to a new server, but I need the new server to forward the QueryString to the old server in case the old server is still waiting for updates, and until I can get my clients migrated over.
The External website calls my webapp with ?MSGID=12345678&RESPONSE=0
eg:
http://dlrnotify.newserver.com/GetResponse.aspx?MSGID=12345678&RESPONSE=0
I need my code behind GetResponse.aspx to process the message locally, and then forward the request to the old server. eg, calling:
http://dlrnotify.oldserver.com/GetResponse.aspx?MSGID=12345678&RESPONSE=0
I don't really want to redirect the user to the old web server, just to pass the querystring on from my app.
I can get the QueryString by calling Response.QueryString.ToString() I just need to know how to post that to the old server without upsetting anything.
Sorry if this is a dumb question, I don't work with web apps very often and am obviously using the wrong search terms.
You can use HttpWebRequest and HttpWebResponse for this. Below is an example to use thses
Uri uri = new Uri("http://www.microsoft.com/default.aspx");
if(uri.Scheme = Uri.UriSchemeHttp)
{
HttpWebRequest request = HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
HttpWebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
Sample Code on how to Post Data to remote Web Page using HttpWebRequest
Uri uri = new Uri("http://www.amazon.com/exec/obidos/search-handle-form/102-5194535-6807312");
string data = "field-keywords=ASP.NET 2.0";
if (uri.Scheme == Uri.UriSchemeHttp)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Post;
request.ContentLength = data.Length;
request.ContentType = "application/x-www-form-urlencoded";
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(data);
writer.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
response.Close();
Response.Write(tmp);
}
After executing your code (process message) on the new server, manually generate a HttpWebRequest which should be to your old server with the same querystring as you already figured out to form.
I have a task which is same as your post. But there is a little more in that.
As we have two web applications, one in asp.net and other in PHP. In both we create user profiles. Now the task is to Create users in Asp.NET application and we need to save the same information in PHP application from Asp.Net app.
I am using the below code for that but it is not wroking, Can you please look at it and let me know what I am missing.
CookieContainer cookies = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(#"http://localhost/admin/config/popup_user_info_brand.php");
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.CookieContainer = cookies; // note this
request.Method = "POST";
string boundary = System.Guid.NewGuid().ToString();
string Username = "admin";
string Password = "admin";
if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
{
request.Credentials = new NetworkCredential(Username, Password);
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Content-Disposition: form-data; name=\"name\"");
sb.AppendLine("Singh");
sb.AppendLine("Content-Disposition: form-data; name=\"username\"");
sb.AppendLine("Singh123");
sb.AppendLine("Content-Disposition: form-data; name=\"email\"");
sb.AppendLine("a#b.com");
sb.AppendLine("Content-Disposition: form-data; name=\"password\"");
sb.AppendLine("P#ssword");
// This is sent to the Post
byte[] bytes = Encoding.UTF8.GetBytes(sb.ToString());
request.ContentLength = bytes.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
requestStream.Close();
using (WebResponse response = request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
HttpContext.Current.Response.Write(reader.ReadToEnd());
}
}
}
}
Note:- PHP web site is a 3rd party, we have no access on code.
Thanks,
Ginni.

Web service Error on retrieve a word document

I get an error when trying to retrieve word document by webservice
HttpWebRequest request;
Uri uri = new Uri(serverUrl +
"/bare.aspx/" + Request.PathInfo);
request = (HttpWebRequest)WebRequest.CreateDefault(uri);
request.KeepAlive = false;
request.AllowAutoRedirect = false;
request.ReadWriteTimeout = -1;
request.Timeout = -1;
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.Method = "POST";
request.ContentType = "application/octet-stream";
// Serialize argument into request stream
Hashtable arguments = new Hashtable();
arguments["templateFile"] = templateFile;
arguments["hSetDataSource"] = hSetDataSource;
arguments["hSetRepeatBlock"] = hSetRepeatBlock;
arguments["messageForEmptyWord"] = messageForEmptyWord;
arguments["hImageBefore"] = hImageBefore;
arguments["hImageAfter"] = hImageAfter;
arguments["hImageInsideRepeater"] = hImageInsideRepeater;
MemoryStream buf = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
fmt.Serialize(buf, arguments);
request.ContentLength = buf.Length;
Stream reqStream = request.GetRequestStream();
buf.WriteTo(reqStream);
reqStream.Close();
buf.Close();
// Retreive word document from response and return it
// TODO: refactor this to stream directly into the response
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
When I check the webservice response (HttpWebResponse resp), I get the following error:
System.Net.WebException: The remote server returned an error: (404) Not Found.
I don't understand where is the problem, thank you in advance for your help.
You are not hitting the endpoint. A 404 means the server could not find the URL you are requesting. Verify your .asmx URL by putting it in your web browser. If that works then make sure you code is using that same URL.

ASP.Net Page HttpWebRequest takes ages to respond

Below is my code (ASP.net web project), but when i debug this asp page it takes ages to retrieve the response ? any idea why is this happening ?
and also the providers of the aURl mentioned to use req.connection="Close" but when i use that throws out an error. (im new to httpwebrequest sigh)
this is the documentation about
connection -This value specifies that
the connection is not to be a
keep-alive connection.
var url = new Uri(#"My URL");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml";
//This Fails but the documentation asks to use this ??
//req.Connection = "Close";
var requestdata = File.ReadAllText(#"D:\request.txt");
//req.ContentLength = requestdata.Length;
StreamWriter myWriter = null;
myWriter = new StreamWriter(req.GetRequestStream());
myWriter.Write(requestdata);
HttpWebResponse objResponse = (HttpWebResponse)req.GetResponse();
This would happen if you have a slow internet connection, or if the URL is on a slow server.
However, try closing the request stream, like this:
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.KeepAlive = false;
req.Method = "POST";
req.ContentType = "text/xml";
using(StreamWriter myWriter = new StreamWriter(req.GetRequestStream())
myWriter.Write(File.ReadAllText(#"D:\request.txt"));
HttpWebResponse objResponse = (HttpWebResponse)req.GetResponse();
Try and turn off the auto detection for a proxy. I have seen where the first request made from an application can be order of magnitude slower because of this:
<system.net>
<defaultProxy>
<proxy autoDetect="False"/>
</defaultProxy>
</system.net>

convert HTTP request code to HTTPS request code

I have got following code witch are sending xml file on HTTP protocol and getting response back as xml file from webserver and its working fine with HTTP protocol, but now i need to send such a XML file to HTTPS protocol (not http) and need to get response as xml file from it. the code to send xml file and get response from HTTP is :
string targetUri = "http://www.hostelspoint.com/xml/xml.php"; /*this will be like: "https://www.hostelspoint.com/xml/xml.php"*/
System.Xml.XmlDocument reqDoc = new System.Xml.XmlDocument();
reqDoc.Load(Server.MapPath("~\\getdetail.xml"));
string formParameterName = "OTA_request";
string xmlData = reqDoc.InnerXml;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);
string sendString = formParameterName + "=" + HttpUtility.UrlEncode(xmlData);
//string sendString = HttpUtility.UrlEncode(xmlData);
byte[] byteStream;
byteStream = System.Text.Encoding.UTF8.GetBytes(sendString);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteStream.LongLength;
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteStream, 0, (int)request.ContentLength);
writer.Flush();
}
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
string respStr = "";
if (request.HaveResponse)
{
if (resp.StatusCode == HttpStatusCode.OK || resp.StatusCode == HttpStatusCode.Accepted)
{
StreamReader respReader = new StreamReader(resp.GetResponseStream());
respStr = respReader.ReadToEnd(); // get the xml result in the string object
XmlDocument doc = new XmlDocument();
doc.LoadXml(respStr);
Label1.Text = doc.InnerXml.ToString();
}
}
There shouldn't be much difference in your code, as HTTP or HTTPS differs only in transport level, not in application level.
What may become a problem here is, if the server certificate used in the targetUri is trusted on your server. In this case the HTTPS identity cannot be verified.

How to dynamically invoke Web Services in .Net

I am writing a Web service client in C# which takes the URL of the web Service, and a web method name.
I want to check if thew Web method actually receives an int and returns a DataTable, and if this is true, it should call it and return the DataTable.
I have found a couple of posts where this is accomplished compiling dynamically the Proxy class.
But for my case this'd be too expensive, because the client is actually a WSS WebPart, and I don't want to do this every time the page is rendered; only when the properties are changed.
In the end of the day web service description is just an XML file. You can grab it by requesting service.asmx?WSDL:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?WSDL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
Once you have service description you can parse it and check method signature. Then, you can invoke the method using HTTP POST:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?HelloWorld");
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";
byte[] data = Encoding.UTF8.GetBytes(
#"<?xml version='1.0' encoding='utf-8'?>
<soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'>
<soap12:Body>
<HelloWorld xmlns='http://tempuri.org/' />
</soap12:Body>
</soap12:Envelope>");
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
If the Web Service is always the same (i.e. the method is the same as well as what it returns) and uit's just the url that might change, then just add a web reference to the project with the webpart in it, the set the Url of the proxy like so:
using (var serviceProxy = new ServiceProxy())
{
serviceProxy.Url = somepropertysetbythewebpart;
// make call to method here
}
After a lot of resarching I found out how to do it. The code of the selected answer is almost there, but I had to add the SOAPAction in the header and also change the ContentType.
Here is the entire code:
var strRequest = #"<soap12:Envelope>
...
</soap12:Envelope>";
string webServiceUrl = "http://localhost:8080/AccontService.svc";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webServiceUrl);
request.Method = "POST";
request.ContentType = "text/xml;charset=UTF-8";
request.Accept = "text/xml";
request.Headers.Add("SOAPAction", "http://tempuri.org/IAccountService/UpdateAccount");
byte[] data = Encoding.UTF8.GetBytes(strRequest);
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string responseXmlString = reader.ReadToEnd();
return new HttpResponseMessage()
{
Content = new StringContent(responseXmlString, Encoding.UTF8, "application/xml")
};

Resources