I'm having an issue with my code not returning Json response. I've never built an API using ASHX before. I have checked my Json string being created and it appears to be good.
The returned serialized json looks like this:
"{""Error"":""Error: Import: Unknown SKU Received!""}"
This is the correct message that should be returned. Instead I get Bad Request as a response. Not generating any errors on my code side.
Code Snippet:
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim oImporter As Importer
Dim oResponse As Domain.Structures.Structures.ReturnResponse
Dim Input_sr As StreamReader
Dim sData As String
Dim bolError As Boolean = False
Dim obj As New Domain.Models.Order.Order
Dim sError As New order_response_error
Dim sResponse As New order_response_success
Try
Input_sr = New StreamReader(context.Request.InputStream)
sData = Input_sr.ReadToEnd
Input_sr.Close()
If context.Request.ContentType.StartsWith("application/json") Then
obj = JsonConvert.DeserializeObject(Of Domain.Models.Order.Order)(sData)
If obj.api_key = ConfigurationManager.AppSettings("api_key") Then
oImporter = New Importer(sData)
oResponse = oImporter.ImportOrder
context.Response.StatusCode = HttpStatusCode.OK
If oResponse.ReturnCode = "Error" Then
bolError = True
context.Response.StatusCode = HttpStatusCode.BadRequest
sError.Error = oResponse.ReturnCode + ": " + oResponse.Message
'sError.Error = String.Format(oResponse.ReturnCode, oResponse.Message)
Else
context.Response.StatusCode = HttpStatusCode.OK
sResponse.vendor_order_id = oResponse.Message
End If
Else
bolError = True
context.Response.StatusCode = HttpStatusCode.Unauthorized
sError.Error = "Error: Access Denied"
'sError.Error = String.Format("Error", "Access Denied")
End If
Else
bolError = True
context.Response.StatusCode = HttpStatusCode.BadRequest
sError.Error = "Error: Invalid content type"
'sError.Error = String.Format("Error", "Invalid content type")
End If
Catch ex As Exception
bolError = True
context.Response.StatusCode = HttpStatusCode.BadRequest
Utils.ErrorEmail("Order Error!", ex, AttachmentName:="Order.xml", AttachmentData:=sData)
sError.Error = String.Format("Error", ex.Message)
End Try
context.Response.ContentType = "application/json"
If bolError Then
context.Response.Write(JsonConvert.SerializeObject(sError))
Else
context.Response.Write(JsonConvert.SerializeObject(sResponse))
End If
End Sub
Error Response from client:
Error:
Cache-Control:
private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?XFxhd2FyZGdyYXBoaWNzLmNvbVxkYXRhXFVzZXJzXG1ob2xtZXNcRGVza3RvcFxDb2xsYWdlXENvbGxhZ2VcQ29sbGFnZS5XZWIuUG9ydGFsXGFwaVx0ZXN0b3JkZXIxLmFzaHg=?=
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods:
GET, POST, OPTIONS
Access-Control-Allow-Headers: X-Requested-With,Content-Type
Date:
Mon, 14 Oct 2019 14:47:57 GMT
Content-Length: 48 bytes
COMPLETE REQUEST HEADERS
pretty
Sec-Fetch-Mode: cors
Origin: chrome-extension://aejoelaoggembcahagimdiliamlcdmfm
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
Content-Type: application/json
Accept: /
Sec-Fetch-Site: cross-site
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: AspxAutoDetectCookieSupport=1
You only have one place in your code where you return a custom message from the server, and with a 'BadRequest', on these lines:
context.Response.StatusCode = HttpStatusCode.BadRequest
sError.Error = oResponse.ReturnCode + ": " + oResponse.Message
That means your business logic is returning this (I can't say appropriately or not). You need to trace through the business logic to find the logic that is presenting the bad SKU message. From that point of view, the ASHX looks to be working correctly.
Related
I'm trying to view the HTTP request being sent/received to twitter. I tried downloading fiddler4 but it's not registering the 401 error and I'm only receiving the 500 page error. Any ideas on how to view the request being sent so I can trouble shoot the reason?
I tried viewing the site as localhost, 127.0.0.1, and machinename.
Dim oAuthRequest As New Dictionary(Of String, String)
oAuthRequest.Add("resource_url", "https://api.twitter.com/oauth/request_token")
oAuthRequest.Add("oauth_callback", Server.UrlEncode("https://www.site.com/callback/"))
oAuthRequest.Add("oauth_consumer_key", "xxxxxxxx")
oAuthRequest.Add("oauth_nonce", Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString())))
oAuthRequest.Add("oauth_signature_method", "HMAC-SHA1")
oAuthRequest.Add("oauth_timestamp", CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString)
oAuthRequest.Add("oauth_token", "authorization_code")
Dim baseFormat As String = "oauth_callback=""{0}""&oauth_consumer_key=""{1}""&oauth_nonce=""{2}""&oauth_signature_method=""HMAC-SHA1""&oauth_timestamp=""{3}""&oauth_version=""" & Uri.EscapeDataString("1.0") & """"
Dim baseString As String = String.Format(baseFormat,
oAuthRequest("oauth_callback"),
oAuthRequest("oauth_consumer_key"),
oAuthRequest("oauth_nonce"),
oAuthRequest("oauth_timestamp"))
baseString = String.Concat("POST&", Uri.EscapeDataString(oAuthRequest("resource_url")), "&", Uri.EscapeDataString(baseString))
oAuthRequest.Add("oauth_signature", SHA1Base64Hash("xxxxxxx&", baseString))
Dim authHeaderFormat As String = "OAuth oauth_callback=""{0}"",oauth_consumer_key=""{1}"",oauth_nonce=""{2}"",oauth_signature=""{3}"",oauth_signature_method=""HMAC-SHA1"",oauth_timestamp=""{4}"",oauth_version=""1.0"""
Dim authHeader As String = String.Format(authHeaderFormat,
Uri.EscapeDataString(oAuthRequest("oauth_callback")),
Uri.EscapeDataString(oAuthRequest("oauth_consumer_key")),
Uri.EscapeDataString(oAuthRequest("oauth_nonce")),
Uri.EscapeDataString(oAuthRequest("oauth_signature")),
Uri.EscapeDataString(oAuthRequest("oauth_timestamp")))
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = CType(WebRequest.Create(oAuthRequest("resource_url")), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Try
Dim response As WebResponse = request.GetResponse()
Catch ex As Exception
Text.text = ex.Message
End Try
If Fiddler shows you a HTTP/500 rather than a HTTP/401, that's because the server is returning HTTP/500. Unless you tell it to do so, Fiddler does not invent responses.
Am trying to create a simple page that connects to an external website, logs in, and then passes a bunch of parameters.
When I run the page I get a bad request 400 error and when I check using Fiddler I can see there are both 401 and 400 errors being returned. Under 'Auth' in Fiddler I see:
"No Proxy-Authorization Header is present.
No Authorization Header is present." < Is this relevant? As when I test using PHP cUrl the page can log in fine and Fiddler says the same under Auth.
Dim UserName As String = "testusername"
Dim password As String = "testpassword"
Dim siteCredentials As New NetworkCredential(UserName, password)
Dim URLAuth As String = "http://service.someurl.com/process.xml"
Dim postString As String = String.Format("customeremailaddress={0}&customername={1}&referenceid={2}&languagecode={3}&expirydays={4}", customeremailaddress, customername, referenceid, languagecode, expirydays)
Dim postBytes As Byte() = Encoding.UTF8.GetBytes(postString)
Const contentType As String = "application/x-www-form-urlencoded"
System.Net.ServicePointManager.Expect100Continue = False
Dim cookies As New CookieContainer()
Dim webRequest__1 As HttpWebRequest = TryCast(WebRequest.Create(URLAuth), HttpWebRequest)
webRequest__1.Method = "POST"
webRequest__1.ContentType = contentType
webRequest__1.CookieContainer = cookies
webRequest__1.ContentLength = postBytes.Length
webRequest__1.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1"
webRequest__1.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
webRequest__1.Referer = "http://service.someurl.com/process.xml"
webRequest__1.Credentials = siteCredentials
Try
Dim requestStream As Stream = webRequest__1.GetRequestStream()
requestStream.Write(postBytes, 0, postBytes.Length)
Dim testcapture As String = requestStream.ToString
Dim thing As String = "stop"
Dim responseReader As New StreamReader(webRequest__1.GetResponse().GetResponseStream())
Dim responseData As String = responseReader.ReadToEnd()
responseReader.Close()
webRequest__1.GetResponse().Close()
Catch ex As Exception
Lbl_ConnTest_error.Text = ex.Message
End Try
Seems the login credentials are not being passed what am I doing wrong? I am obviously using vb in an asp.net application but am connecting to an XML file held on Linux Apache, does this have any implications at all?
Fiddler appears to be doing strange things for me now so if anyone else can see anything using Fiddler a link to the test file is here:
http://www.filemanage.co.uk/Pubs/Default.aspx
When I ran my web application code I got this error on this line.
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){}
Actually when I ran my url directly on browser.It will give proper o/p but when I ran my url in code. It will give exception.
Here MyCode is :-
string service = "http://api.ean.com/ean-services/rs/hotel/";
string version = "v3/";
string method = "info/";
string hotelId1 = "188603";
int hotelId = Convert.ToInt32(hotelId1);
string otherElemntsStr = "&cid=411931&minorRev=[12]&customerUserAgent=[hotel]&locale=en_US¤cyCode=INR";
string apiKey = "tzyw4x2zspckjayrbjekb397";
string sig = "a6f828b696ae6a9f7c742b34538259b0";
string url = service + version + method + "?&type=xml" + "&apiKey=" + apiKey + "&sig=" + sig + otherElemntsStr + "&hotelId=" + hotelId;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "text/xml";
request.ContentLength = 0;
XmlDocument xmldoc = new XmlDocument();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
xmldoc = (XmlDocument)JsonConvert.DeserializeXmlNode(responsedata);
xmldoc.Save(#"D:\FlightSearch\myfile.xml");
xmldoc.Load(#"D:\FlightSearch\myfile.xml");
DataSet ds = new DataSet();
ds.ReadXml(Request.PhysicalApplicationPath + "myfile.xml");
GridView1.DataSource = ds.Tables["HotelSummary"];
GridView1.DataBind();
}
The error is providing all you need.
The method POST might not be supported by the api or for this call.
This should work. Try changing the method to "GET"
request.Method = "GET";
In Browser you are sending a GET request to the api. You should do the same in the code as well.
For XML Response:
request.Method = "GET";
request.ContentType = "text/xml; charset=UTF-8";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
request.Accept = "application/xml";
request.ContentLength = 0;
I am making a request to a site, they are using JSON for exchanging data. Hence I made the following request but it is giving an error -The remote server returned an error: (400) Bad Request.
URL3 is a string
httpWebRequest = (HttpWebRequest)WebRequest.Create(URL3);
httpWebRequest.Method = "POST";
httpWebRequest.Host = "url";
httpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
httpWebRequest.KeepAlive = true;
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.Referer = "url2";
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
httpWebRequest.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
string postData = "";
postData += "{\"prefixText\":\"hyderabad\",\"count\":10,\"contextKey\":\"45\"}";
StreamWriter requestWriter = new StreamWriter(httpWebRequest.GetRequestStream());
requestWriter.Write(postData); //posting the data
requestWriter.Close();
**httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();**
responseStreamReader = new StreamReader(httpWebResponse.GetResponseStream());
string responseData_3 = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
Please help me.
Hi i'm getting encoding problems with the code below any ideas?
string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string retVal = reader.ReadToEnd();
Response.Write(retVal);
}
My Screenshoot is like that;
Thanks for your help!
Google is notorious for checking the useragent HTTP header. Because you're not setting it its encoding everything as ISO-8859-9. The simple solution is to manually set the UserAgent property of the HttpWebRequest. Set it to anything you want, below is a Firefox string (and an extra Using block):
string url = "http://www.google.com/ig/api?weather=istanbul,TR&hl=tr";
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
string retVal = reader.ReadToEnd();
Console.WriteLine(retVal);
}
}