web api returning invalid json - Unexpected token - ajax

I have a web api2 controller returning a collection of complex types.
This setup has been working for some time, until it started choking on a record today.
It appears that one of the objects (out of 122), is now breaking JSON.parse on the client.
Fiddler is also not able to parse JSON. As soon as i skip the "bad" object, valid JSON is returned.
here are the headers from the breaking response:
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcZGV2XEJTR1xBcHBzXENhbXBGb3JjZVx0cnVua1xQZXJtYWwuQlNHLkNhbXBGb3JjZS5XZWJcYXBpXGNhbXBcdGVtcGxhdGVz?=
Persistent-Auth: true
X-Powered-By: ASP.NET
Date: Tue, 18 Mar 2014 00:50:14 GMT
Content-Length: 1312
if i look at the serialized object string on the client, and paste it into jsonLint it points to this area:
"HtmlValue": "<html>\n\n<body...
this looks pretty much the same as all the "good" objects.. so i'm a bit stumped.
since web api is encoding the response as JSON, why would it allow breaking characters?
update
here is the breaking json (i retrieved it on client prior to deserialization:
[
{
"$id": "1",
"Id": "00Xg0000000MBGoEAO",
"Name": "Template Test",
"Body": null,
"HtmlValue": "<html>\n\n<body lang=EN-US style='tab-interval:.5in'>\n\n<div class=Section1>\n\n<p class=MsoNormal><span class=SpellE><span style='font-size:20.0pt;line-height:\n115%;font-family:\"Franklin Gothic Book\",\"sans-serif\"'></span></span><span\nstyle='font-size:20.0pt;line-height:115%;font-family:\"Franklin Gothic Book\",\"sans-serif\"'><o:p></o:p></span></p>\n\n<p class=MsoNormal>testing </p>\n\n<p class=MsoNormal><o:p> </o:p></p>\n\n</div>\n\n
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Chrome"}
</script>
<script type="text/javascript" src="http: //localhost: 61319/6cd9cb905b1e4b5bb51cb5a36ea0bd17/browserLink" async="async"></script>
<!-- End Browser Link -->
</body>\n\n</html>",
"Subject": "Test",
"IsActive": true
}
]
the plot thickens.
this part is being inject into the HTML property
<!-- Visual Studio Browser Link -->
<script type="application/json" id="__browserLink_initializationData">
{"appName":"Chrome"}
</script>
<script type="text/javascript" src="http: //localhost: 61319/6cd9cb905b1e4b5bb51cb5a36ea0bd17/browserLink" async="async"></script>
<!-- End Browser Link -->
when i step through the code on the server, this snipped is not there, but when i view it in fiddler, i can see it injected in the response!

Related

Not able to consume WEB API hosted in same server

Below web API returns JSON for the given ID.
http://aws-av-devser/Assigning_ID/api/QidMasters/2
It's working as expected in postman.
but when I try to consume this web API in different projects on the same server. I am getting
404 Not found Error
Below is the code to consume the web API
var uri = "http://aws-av-devser/Assigning_ID/api/QidMasters/2";
var response = await httpClient.GetAsync(uri);
Error Message :
{
StatusCode: 404,
ReasonPhrase: 'Not Found',
Version: 1.1,
Content: System.Net.Http.HttpConnectionResponseContent,
Headers:
{
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 17 Jun 2022 17:59:28 GMT
Connection: close
Content-Type: text/html; charset=us-ascii
Content-Length: 315
}
}
Please correct me if I am missing something

Which IIS config causes the "405 Method not allowed" error for specific calls?

In our current WebAPI calls, only a few specific ones are returning the 405 error message (405 Method not allowed), the rest are working okay. The ones that are failing are only failing in a specific environment, in all the other environments all calls are returning 200 and everything is kosher.
Which IIS setting or system setting can cause this ? I am zooming in on this because this looks more like a systems/config issue.
Request URL : <hostname/GetAllStuff?userId=johndoe&sortByCustom=CreatedDate&sortByOrder=desc
Request Method: GET
Status Code: 405 Method Not Allowed
Remote Address: 172.72.78.33:443
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS
Access-Control-Allow-Origin: *
Allow: GET,POST,DELETE,PUT
Cache-Control: no-cache
Content-Length: 136
Content-Type: application/json; charset=utf-8
Date: Tue, 06 Nov 2018 17:16:28 GMT
Expires: -1
The Response looks like this. What is strange is that ALL the API calls are 1.0 (api-version: 1.0) yet only a couple of calls throw this error and that too in a specific environment.
{
"Error": {
"Code": "UnsupportedApiVersion",
"Message": "The requested resource with API version '1.0' does not support HTTP method 'GET'."
}
}

Invisible Google reCaptcha returns 410 when verifying user's input

We're using invisible reCaptcha and, once in a while, Google's Javascript code makes a request to Google's servers receiving a response status 410, instead of 200.
We don't have control over it as the request is being made by Google's reCaptcha Javascript code.
If the challenge has been presented to the user, the following is an example of what the failing request looks like:
GET https://www.google.com/recaptcha/api2/payload?c=03AOPBWq_EYB...
And the response is:
HTTP/1.1 410 Gone
<HTML>
<HEAD>
<TITLE>Gone</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Gone</H1>
<H2>Error 410</H2>
</BODY>
</HTML>
It fails about 10% of the time. Below is a "history" of HTTP requests:
Request #1
POST https://www.google.com/recaptcha/api2/reload?k=6LcqZCEU...
v:r20170515161201
reason:fi
bcr:[1943341955,-150...
...
HTTP/1.1 200 OK
content-type: application/json
...
)]}'
["rresp","03AOPBWq_EYBOYkGkn-1S...",null,600,["pmeta",null,null,null,
null,[[["TileSelectionStreetSign",null,3,4,4,null,null,[]
]
,["dress",null,3,4,4,null,null,[]
]
]
,[]
]
]
,"multicaptcha",null,
["bgdata","Ly93d3cuWk5rOHFMZDlvNDZFa..."]
]
The above response looks like invalid JSON but is expected as detailed here
Request #2
GET https://www.google.com/recaptcha/api2/payload?c=03AOPBWq_EYBOYk...
...
HTTP/1.1 200 OK
content-type: image/jpeg
content-length: 50528
...
<JPEG>
Request #3
POST https://www.google.com/recaptcha/api2/replaceimage?k=6LcqZCEUAA...
v:r20170515161201
c:03AOPBWq_EYBOYkGkn-1SplFL...
ds:[[5,6,9,10,13,14]]
HTTP/1.1 200 OK
content-type: application/json
...
)]}'
["dresp","03AOPBWq-Iyck5GCpx86hk57XSxF-9b4GMaDeujP...",[]
,null,[]
]
Request #4 (the failing one)
GET https://www.google.com/recaptcha/api2/payload?c=03AOPBWq_EYBOYk...
...
HTTP/1.1 410 Gone
content-type: text/html
...
<HTML>
<HEAD>
<TITLE>Gone</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Gone</H1>
<H2>Error 410</H2>
</BODY>
</HTML>
This is basically because the session has expired. When ever you receive an error 410 (i.e. not successful and you still wish to upload the file), you must start a new session. Please have a look at the below link for details :
https://www.rfc-editor.org/rfc/rfc7231#section-6.5.9
Your call is GET. You need POST
Ref: https://www.google.com/recaptcha/api2/payload?c=03AOPBWq_EYB..

unable to make a remote POST to Web API (sending string) - not sure what happens

I have a web api method:
[HttpPost]
public IActionResult Post([FromBody]string entryInJson)
{ .... }
This method is hit by a remote domain, so CORS is needed. As i wasn't successful in finding the relevant cs file in my mvc6 app, i used this solution in web.config:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
When I do the post, using online tools like http://requestmaker.com/, i am getting this:
Request Headers Sent:
POST /api/Entries/ HTTP/1.1
Host: justalk.tukuoro.com
Accept: */*
Content-Type: text/plain
Content-Length: 179
Response Headers:
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 0
Expires: -1
Location: https://justalk.tukuoro.com/Account/Login?ReturnUrl=%2FHome%2FError
X-Powered-By: ASP.NET
Access-Control-Allow-Origin: *
Date: Mon, 16 May 2016 05:25:53 GMT
Now, it seems like it is trying to redirect me (302) but to the error page, and it is not sending anything back from the post method, which returns:
return new ObjectResult(true);
I am not sure what is going on:
Am I getting to the right controller? i have code that is supposed to log the incoming string but it does not create the log.
If it is not working? why? is the response header telling me something I don't understand?
Am I doing it right?
thank you for your time!
if you want send json post request this entryInJson must be object type not string
for example
[HttpPost]
public IActionResult Post([FromBody]EntryInJson entryInJson)
{ .... }
chat comment
the code doing the http request to my post method - how does it convert this class "RemoteEntry" to JSON data
http://www.newtonsoft.com/json/help/html/serializingjson.htm
Update :
302 is not an error but a redircet to a tempoaray location. you could resend the request to the new location received in the response header.
and it's propably a server misconfiguration issue then.
modSecurity firewall blocking your requests an making automatics redirections (302).

Post request to golang server using polymer core-ajax?

I am trying to make a POST request using polymer core-ajax to server runnung golang. After a lot of search (because i am new to this stuff) i ended up with the following code. Also, GET request is working perfect. POST parameters i dont understand how to pass using core-ajax.
<polymer-element name="register-user" attributes="url">
<template>
<core-ajax id="ajaxSubmit" url="{{url}}" contentType="application/json" handleAs="json" method="post" on-core-response="{{response}}"></core-ajax>
<style type="text/css">
</style>
</template>
<script>
Polymer({
buttonListener: function() {
var data = '{"Name":"'+ this.name +'", "Email":"'+ this.email +'"}';
this.$.ajaxSubmit.data = data;
this.$.ajaxSubmit.go();
console.log(data);
},
response: function(oldValue){
console.log(this.response);
}
});
</script>
</polymer-element>
above code returns 500 (Internal Server Error) however when i make a POST request using curl i.e
curl -i -H 'Content-Type: application/json' -d '{"Name":"Batman",
"Email":"batman#gmail.com"}' http://so.me.ip.ad:8080/register
it works as it should and returns
HTTP/1.1 200 OK
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Wed, 29 Apr 2015 05:40:15 GMT
Content-Length: 117
{
"id": 3,
"name": "Batman",
"email": "batman#gmail.com",
"createdAt": "2015-04-29T05:40:15.073491143Z"
}
also, i have a CORS middleware set up on server i.e
api.Use(&rest.CorsMiddleware{
RejectNonCorsRequests: false,
OriginValidator: func(origin string, request *rest.Request) bool {
return origin == "http://0.0.0.0:8000"
},
AllowedMethods: []string{"GET", "POST", "PUT"},
AllowedHeaders: []string{
"Accept", "Content-Type", "X-Custom-Header", "Origin"},
AccessControlAllowCredentials: true,
AccessControlMaxAge: 3600,
})
What am i doing wrong? Any feedback will be of great help! Thanks ^.^
Edit : here is a little more info if it can help..
I think CORS is a red herring. The problem may be that you are sending the data form-encoded and not as json. I found a bug from a user with a similar problem.
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Fri, 12 Dec 2014 04:29:59 GMT
Content-Length: 71
{
"Error": "invalid character '\\'' looking for beginning of value"
}
Perhaps you should use .body instead of .data? See this answer.
From the polymer documentation:
body: Optional raw body content to send when method === "POST".
Example:
<core-ajax method="POST" auto url="http://somesite.com"
body='{"foo":1, "bar":2}'>
</core-ajax>

Resources