How do I get responseText when server sends 500 error on WebRequest.Create(URL).GetResponse() - asp.net

I am calling a json web service that sends error messages by setting StatusCode to 500 and then sending error message as response text (such as { "Message": "InvalidUserName" } ).
Problem is that ASP.NET does not give me the response text if web service sends statuscode 500.
try
{
WebRequest request = WebRequest.Create(URL);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string result = streamReader.ReadToEnd();
streamReader.Close();
response.Close();
return result;
}
catch (Exception e)
{
// If web service sends 500 error code then we end up here.
// But there is no way to get response text :-(
}
Is there a way to solve this? Also: I am controlling the web service, so it might be a solution to do some change their. (Note: I need to call the service using plain WebRequest stuff - in this case it will not work with other methods such as adding as WebReference etc)
Any ideas?

Catch WebException instead. It has a Response property containing the response. Be sure to check for null before using it.

Related

Getting Facebook Page Feed ( using graph api ) in asp.net, receiving error "Unsupported Browser"

I am trying to get facebook page feed ( public posts) which does not require any access token.
here's the url
https://www.facebook.com/feeds/page.php?format=json&id=1393547494231876
when i run this in browser where id= any facebook page id. it returns first 25 public posts in json format.
but when i run this in my code to get json result facebook return a page saying "unsupported browser"
this is my method . i pass it facebook page id to get posts..
public static String GetPosts(string PageId)
{
string id = PageId;
string apilink = "https://www.facebook.com/feeds/page.php?format=json&id=";
HttpWebRequest request = WebRequest.Create(apilink + id) as HttpWebRequest;
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
String result = reader.ReadToEnd();
return result;
}
}
Here's the result that i get in return string
Result Image String
and so on remaining page returned.
Can somebody help me how to get it working??
Update
Found Answer...
I Have To Set User agent to make Facebook think i am a browser..
so just added
request.UserAgent = ".NET Framework";
and i worked.
Thanks to All.
Found Answer... I Have To Set User agent to make Facebook think i am a browser.. so just added request.UserAgent = ".NET Framework"; and i worked. Thanks to All.

The remote server returned an error: (400) Bad Request while consuming a WCF Service

Please view the code given below. While the debug reaches the request.GetResponse() statement the error has been thrown.
Uri uri = new Uri(address);
string data = "<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><s:Body><HasRole xmlns='http://tempuri.org/'><userName>" + sid + "</userName><role>" + role + "</role></HasRole></s:Body></s:Envelope>";
data.Replace("'", "\"");
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
if (uri.Scheme == Uri.UriSchemeHttps)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";// WebRequestMethods.Http.Post;
request.ContentLength = byteData.Length;
request.ContentType = "application/soap+xml; charset=UTF-8"; // "text/xml; charset=utf-8";
//request.ContentType = "application/x-www-form-urlencoded";
//Stream requestStream = request.GetRequestStream();
using (Stream writer = request.GetRequestStream())
{
writer.Write(byteData, 0, byteData.Length);
}
//writer.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string tmp = reader.ReadToEnd();
Response.Close();
Response.Write(tmp);
}
I would double check the URL. If the URL looks ok on the client side, I recommend looking at access logs on your server to see what URL is being hit. 4xx errors mean a resource was not found. If the endpoint was correct, but the request was fubared, you would get a 5xx error code. (Assuming that your server side frameworks uses standard HTTP Response Codes).
As has been mentioned you should use the 'Add Service Reference' to access the WCF service from a .NET client. However, if you're emulating trying to connect from a non .NET client, your soap envelope is missing the header information.
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">
specify your action namespace here (e.g. http://tempuri.org/ISomeService/Execute)
</Action>
</s:Header>

How to do httpPost to a webservice which accepts a byte array of a file using c#

I am working on an API kind of project,
I have wrote a WebMethod (not exactly. I am using MVC to create REST like API)
public UploadFileImage(string employeeId, byte[] imageBytes, string imageName)
{
// saves the imagebyte as an image to a folder
}
the web service would be consumed by a web app, or windows or even iphone or such portable stuffs. I am testing my web service using a web app, by simple httpPost.
string Post(Uri RequestUri, string Data)
{
try
{
HttpWebRequest request = HttpWebRequest.Create(RequestUri) as HttpWebRequest;
request.Method = "POST";
request.ContentType = IsXml.Checked ? "text/xml" : "application/x-www-form-urlencoded";
byte[] bytes = Encoding.ASCII.GetBytes(Data);
Stream os = null; // send the Post
request.ContentLength = bytes.Length; //Count bytes to send
os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
return streamReader.ReadToEnd();
}
catch (Exception ex)
{
return ex.Message;
}
}
This code works fine for evey method like, AddEmployee, DeleteEmployee etc. THe parameter Data is of form "Id=123&name=abcdefgh&desig=Developer",
How I call any other function is
Post(new Uri("http://localhost/addemployee"),"name=abcd&password=efgh")
where post is the function i wrote.
All good for all functions. Except that I dont know how to consume the above mentioned function UploadFileImage to upload an image?
Thanks
Try encoding the imageBytes as Base64.
From your code snippet is not too clear how you call UploadFileImage, that is how you convert its parameters tripplet into Data.
That is why my answer is quite generic:
In general, you'd better transfer your image file by
request.ContentType = "multipart/form-data; boundary=----------------------------" + DateTime.Now.Ticks.ToString("x");
Please allow me to refer you to a sample at StackOverflow on how to format a multipart request. I am sure that if you google, you shall find a lots of detailed examples and explanations as well.
I hope this helps :-)

User authentication through REST web service on a different domain - asp.net

I am looking to connect to a web service on a different domain in order to authenticate users. The Web Service itself is a RESTful service, written in Java. Data is passed to and from it in JSON.
I initially tried to connect using jQuery (see below)
function Login()
{
$.ajax({
url: "http://www.externaldomain.com/login/authenticate",
type: "POST",
dataType: "json",
contentType: "application/json",
data: "{'emailAddress':'bob#bob.com', 'password':'Password1'}",
success: LoadUsersSuccess,
error: LoadUsersError
});
}
function LoadUsersSuccess(){
alert(1);
}
function LoadUsersError(){
alert(2);
}
However, when checking on Firebug, this brought up a 405 Method Not Allowed error.
At this stage, as this is the first time I've really worked with web services, I really just wondered whether this was the best way to do things? Is it worth persevering with this method in order to find a solution, or am I best to maybe try and find a server-side answer to this issue? If so, does anyone have any examples they could post up?
Many thanks
Doing cross-domain web service calls in a browser is very tricky. Because it's a potential security vulnerability, browsers block these types of requests. However, there is a workaround called JSONP. If you use JSONP instead of plain JSON, you should be able to make the cross-domain request.
Right ok, to update where I am, I checked in firebug and on the external server and the reason why I'm getting a 405 error is because I'm doing a Get rather than a Post.
What I need to do is send the username and password, then receive a GUID back which will then be used for any future requests. I thought by having 'type:post' in the code would be enough but apparently not. Anyone know where I might be going wrong here? As I said, a novice to web services and nothing I have tried from looking online has had any effect. Many thanks
Ok, I got the problem solved, and I did it by going back to C# and doing it there instead of using jQuery or JSONP and I used Json.Net for handling the data received. Here is the code:
protected void uxLogin_Click(object sender, EventArgs e)
{
StringBuilder data = new StringBuilder();
data.Append("{");
data.Append("'emailAddress': '" + uxEmail.Text + "', ");
data.Append("'password': '" + uxPassword.Text + "'");
data.Append("}");
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
string url = System.Configuration.ConfigurationManager.AppSettings["AuthenticationURL"].ToString();
string JSONCallback = string.Empty;
Uri address = new Uri(url);
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/json";
// Create a byte array of the data we want to send
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
JSONCallback = reader.ReadToEnd().ToString();
}
if (!String.IsNullOrEmpty(JSONCallback))
{
JObject jObject = JObject.Parse(JSONCallback);
if ((bool)jObject["loginResult"] == false)
{
string errorMessage = jObject["errorMessage"].ToString();
int errorCode = (int)jObject["errorCode"];
}
else
{
string idToken = jObject["idToken"].ToString();
Session["Userid"] = idToken;
Response.Redirect("~/MyDetails.aspx");
}
}
else
{
uxReturnData.Text = "The web service request was not successful - no data was returned";
}
}
Thanks anyway :)

Asp.net HttpWebResponse - how can I not depend on WebException for flow control?

I need to check whether the request will return a 500 Server Internal Error or not (so getting the error is expected). I'm doing this:
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.OK)
return true;
else
return false;
But when I get the 500 Internal Server Error, a WebException is thrown, and I don't want to depend on it to control the application flow - how can this be done?
I think this MSDN articles will help you:
http://msdn.microsoft.com/en-us/library/system.net.webexception.status.aspx
Indeed, given the example at msdn, there is no way to not depend on the exception for control flow. Here's the example they give:
try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site");
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("This program is expected to throw WebException on successful run."+
"\n\nException Message :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}
Apparently, sometimes you do have to go down that route. Ah, well.

Resources