Intermittent 411 error for AJAX call on different browsers - c#

I have an older C# MVC 4.7 web app that has a specific $.post call. Running locally from Visual Studio 2019 in any browser, I have no problem at all. The call goes through and posts the partial page to the div as expected. Running from our test URL, it gives me an error in Edge and Chrome, but not in Firefox. It returns a 411 error, which I know means it's a content length issue. The problem is that others accessing the site do not run across that issue in any browser. Since it works on others' machines and on one particular browser on my local machine, I suspect it's a security setting or something along those lines for that particular site. I've cleared out the settings, reset to factory default, removed extensions, assured that's up-to-date and tested it with and without antivirus software interaction.
This fails:
$.post('/Controller/Method', function (data) {
$('#container').html(data);
});
But this works:
$.post("/Controller/OtherMethod", { paramOne: varOne, paramTwo: varTwo }, function (data) {
$("#container").html(data);
});
Both functions work in Firefox when running from the test URL, only second one works in Edge/Chrome from test URL.
Any ideas on what I might need to check?
Here's the header from the failing call in Dev Tools:
General
Request URL: https://[url]/Controller/Method?param=123
Request Method: POST
Status Code: 411
Remote Address: [remote_ip]
Referrer Policy: strict-origin-when-cross-origin
Response Headers
content-type: text/html; charset=us-ascii
date: Thu, 19 Aug 2021 17:08:18 GMT
server: Microsoft-HTTPAPI/2.0
Request Headers
:authority: [url]
:method: POST
:path: Controller/Method?param=123
:scheme: https
accept: /
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
content-length: 0
cookie: [cookie info]
origin: https://[url]
pragma: no-cache
referer: https://[url]/Controller/Method?param=123
sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google
Chrome";v="92"
sec-ch-ua-mobile: ?0
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-origin
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159
Safari/537.36
x-requested-with: XMLHttpRequest

After experiencing the same problem in both Chrome and Edge across two different websites, I think I have the answer:
The problem appears to be BitDefender antivirus.
If I disable BitDefender protection, the post requests succeed.
EDIT:
Bizarrely, if I then re-enable BitDefender protection, the issue doesn't come back.
After stumbling across the solution, I found a few references to people having the same problem: https://community.bitdefender.com/en/discussion/88573/status-411-length-required-during-browsing https://support.mozilla.org/en-US/questions/1344632

Related

My Simple C# HTTP Server: Embedded HTML Links Don't Work in Edge Browser

I have a basic http file server with a simple API written in WPF/C# that's meant for users to access locally or from their local network. It usesSystem.Net.HttpListener. So the URL to load a jpg for example:
http://localhost:8085/?getfile=d:/temp/Patern_test.jpg
works perfectly in every browser including Edge. No problems. But if I embed any link to my file server in an HTML file:
<html>
<body>
<object data="http://localhost:8085/?getfile=d:/temp/Patern_test.jpg">
</object>
</body>
</html>
Then it only works in Chrome and Firefox. Not Edge or IE 11. I've tried image, video, and iframe tags and the result is the same. I've tried replacing localhost with the actual IP and calling it remotely, same results.
However if I embed a link to another site instead of to my server, it works fine on all browsers:
<html>
<body>
<object data="https://upload.wikimedia.org/wikipedia/commons/d/db/Patern_test.jpg">
</object>
</body>
</html>
So it seems there's something about my server that Edge doesn't like. Can anyone help me understand what this could be? Here is a comparison of the headers:
My Local HTTP Server (Edge doesn't like this):
Request URL: http://localhost:8085/?getfile=d:/temp/Patern_test.jpg
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:8085
Referrer Policy: no-referrer-when-downgrade
Response Headers
HTTP/1.1 200 OK
Content-Length: 36623
Content-Type: image/jpg
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 30 Aug 2018 10:50:03 GMT
Request Headers
GET /?getfile=d:/temp/Patern_test.jpg HTTP/1.1
Host: localhost:8085
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
DNT: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Wikipedia Server (Edge likes this) :
Request URL: https://upload.wikimedia.org/wikipedia/commons/d/db/Patern_test.jpg
Request Method: GET
Status Code: 304
Remote Address: 198.35.26.112:443
Referrer Policy: no-referrer-when-downgrade
Response Headers
accept-ranges: bytes
access-control-allow-origin: *
access-control-expose-headers: Age, Date, Content-Length, Content-Range, X-Content-Duration, X-Cache, X-Varnish
age: 39865
content-type: image/jpeg
date: Thu, 30 Aug 2018 11:12:24 GMT
etag: 77d2a6bf840622331df62963174df72d
last-modified: Mon, 07 Oct 2013 13:46:55 GMT
status: 304
strict-transport-security: max-age=106384710; includeSubDomains; preload
timing-allow-origin: *
via: 1.1 varnish (Varnish/5.1), 1.1 varnish (Varnish/5.1), 1.1 varnish (Varnish/5.1), 1.1 varnish (Varnish/5.1)
x-analytics: https=1
x-cache: cp1090 hit/1, cp2022 pass, cp4021 hit/3, cp4021 miss
x-cache-status: hit-local
x-client-ip: 47.154.205.235
x-object-meta-sha1base36: 8ktqmjes2nx4xcpy5h6v7o1sh6yao09
x-timestamp: 1381153614.85319
x-trans-id: tx76f1f3c2f9384f9eaff9b-005b871d52
x-varnish: 207150442 204346683, 73416305, 38868466 25417638, 135979082
Request Headers
:authority: upload.wikimedia.org
:method: GET
:path: /wikipedia/commons/d/db/Patern_test.jpg
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: max-age=0
cookie: WMF-Last-Access-Global=26-Aug-2018; GeoIP=US:CA:Thousand_Oaks:34.21:-118.88:v4
dnt: 1
if-modified-since: Mon, 07 Oct 2013 13:46:55 GMT
if-none-match: 77d2a6bf840622331df62963174df72d
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
Also I should mention that I very much need this to work in Edge because it will be used in conjunction with a WebView control in a UWP app.
UPDATE:
It turns out this issue only happens under two conditions, neither of which actually matter to me:
The link is embedded in a local html file that I load directly in Edge.
If I use UWP's WebView.NavigateToString(stringOfHtml).
If the HTML is served directly from the local server using WebView.Navigate(Uri) then the embedded link works fine.
This leads me to suspect this is some kind of low-level security measure going on to prevent dynamically created html from running malicious code. Just a thought.

Angular Post to Asp.Net (not Core) Web Api Error 415 on IIS

I'm going completely nuts in making a simple Web Api call to work and I'm quite frustrated because things are much more complicated than they should be.
I created an extremely simple Web Api (for testing) that is consumed by an Angular 6 client and I was able to make it to work if I self-host it locally but if I publish it to my Win10 local IIS (that is the way it will work when deployed to a server) then the request to Web Api fails with error 415 "Unsupported Media Type".
The weird thing is that if I make the request to the self-hosted Web Api (which works) browser network tab is quite different than requesting to IIS published version.
This is my Web Api method:
[HttpPost]
[HttpOptions]
public void Post([FromBody]Credentials cred)
{
string strTest = "I'm doing just nothing";
}
I have to mention that it took me a whole morning to make it to work even self-hosted because of CORS and the key was adding the [HttpOptions] in method header.
Class Credentials:
public class Credentials {
public string Username { get; set; }
public string Password { get; set; }
}
Angular post code:
let headers={
headers: new HttpHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
})
}
return this.http.post<any>('http://localhost:9810/api/Login', JSON.stringify({username, password}), headers) ...
Network tab info when self-hosted (working one):
General:
Request URL: http://localhost:9000/api/Login
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: [::1]:9000
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Content-Length: 0
Date: Thu, 30 Aug 2018 09:24:50 GMT
Server: Microsoft-HTTPAPI/2.0
Request Headers:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9,en;q=0.8
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:9000
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
Network tab info when published to local IIS (NOT working one):
General:
Request URL: http://localhost:9810/api/Login
Request Method: OPTIONS
Status Code: 415 Unsupported Media Type
Remote Address: [::1]:9810
Referrer Policy: no-referrer-when-downgrade
Response Headers:
Content-Length: 801
Content-Type: application/json; charset=utf-8
Date: Thu, 30 Aug 2018 08:57:58 GMT
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Request Headers:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: es-ES,es;q=0.9,en;q=0.8
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:9810
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36
So, as you see, when the Web Api is published to IIS the output in network tab is different and the header is not arriving.
I'm completely stuck and frustrated my friends. Please help.
Edit 1: I add my WebApiConfig where you can see I enable cors just in case.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("http://localhost:4200", "*", "*");
config.EnableCors(cors);
}
}
Again, I'll never understand why things are so complicated (and sometimes contradictory) when they shouldn't.
The way I was able to make the request successfully in self-hosted Web Api as well as published in IIS Web Api was to replace application/json by application/x-www-form-urlencoded but why? This is a contradiction as I'm clearly sending json data.
Anyway, not it works so I'll mark my own question as resolved.
let headers={
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
})
}

Fundamental Misunderstanding About CORS and Ajax Call

I have code that works, but I'm having a difficult time making the connection as to why it works.
I have code in an AngularJS factory function that makes this call:
$http.get('http://webServerName/PrestoWebApi/api/apps/')
And this is the Web API controller (C#):
[EnableCors(origins: "http://webServerName", headers: "*", methods: "*")]
public class AppsController : ApiController
The source of the call would be a user's computer, for example, a laptop with the name JoesLaptop. And that laptop could run anywhere. (Currently, this is all running inside one LAN, but the user could be anywhere.)
So why does specifying the web server name within the EnableCors attribute work? Isn't the request coming from the browser on Joe's laptop and not from the web server itself?
Edit
If I remove the EnableCors attribute, I get this error in the F12 tools in the browser:
XMLHttpRequest cannot load http://webServerName/PrestoWebApi/api/apps/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://webServerName' is therefore not allowed access.
Edit 2
Request:
GET http://fs-6103.fs.local/PrestoWebApi/api/apps/ HTTP/1.1
Host: fs-6103.fs.local
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: http://fs-6103
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
Referer: http://fs-6103/PrestoWebApi/app/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
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/7.5
Access-Control-Allow-Origin: http://fs-6103
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 31 Oct 2014 18:30:05 GMT
Content-Length: 2931171
If webServerName is rendering an HTML page that is starting an asynchronous request to webServerName, then CORS doesn't apply and your server will serve that resource anyway.
I'm pretty sure that must be your case.
UPDATE
Based on the latest edits of the question and the comments that the OP has made bellow this answer, this is what must be happening.
The HTTP server that it's serving both the main HTML page and the API resource is the same, therefore there shouldn't be any need to EnableCORS. However, according to the headers of the Request the page is being served from http://fs-6103 and the $http.get is made to http://fs-6103.fs.local. That should explain everything.
UPDATE 2
Ok, I'm willing to bet that this is what's happening here:
The main page is being served by http://fs-6103
The $http.get is made towards: http://fs-6103.fs.local/
So far I'm not speculating, this is what the request is saying
The OP must have [EnableCors(origins: "http://fs-6103", headers: "*", methods: "*")] set into the API controller.
When this is disabled the OP is getting the error: No 'Access-Control-Allow-Origin' header is present on the requested resource, as it should be expected. And when the OP enables it everything works as expected.
Browsers/clients handle the security, and generally restrict things to single origin, meaning they only accept stuff from the server they made the request to. Enabling cors in the header (ACAO) or wherever lets that server tell the browser, "hey those other Cross origin resources are with me." The browser will generally go along with that.

Fragmented GET request when using websocket in Firefox

I am currently developing a small websocket server in C# to handle connections from browsers.
I mostly used the code from Mozilla and Microsoft (respectively here and there). Unfortunately, when I try to connect to my basic server from a browser (the script was taken from websocket.org), the GET request appears to be fragmented...
I would like to understand why the GET request is divided into two parts. Let me show you my code and the output I get from it.
Code:
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.UTF8.GetString(bytes,0,i);
Console.WriteLine("Received: {0}", data);
}
Output:
Received: GET / HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Received:
Sec-WebSocket-Version: 13
Origin: null
Sec-WebSocket-Key: 2QYy54zGPPKAkNyPgFjkbw==
Connection: keep-alive, Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
I also tried on Chrome to see how different it would be and by running the same code and the same script in the browser I get the following output:
Received: GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.1
Origin: null
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: mp5oLqe/YaQAxRksoVZWKg==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: permessage-deflate; client_
Received: max_window_bits, x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
I see nothing wrong in the output with Chrome, so I don't really understand why the request is divided when using firefox...
I could merge the two parts of the request together, but if I understood the RFC6455 properly, any bad request should be dropped by the server.
Any suggestion?
Thank you very much.
That is totally fine. Maybe Firefox is sending the information in a way (slower) you have to read twice the network buffer but this is OK. It seems it is sending the common information that never change first, and after the information about the websocket (that has to be generated each time) last, probably to reduce the "time for the first byte".
Regarding to the HTTP protocol, the header ends when there is an empty line, so as long you do not get one and the network buffer contains information (readed!=0), you can continue reading the header.
Usually, you are going to find this situation often when doing network programming. You have to continue reading until the network stream says readed=0.

How do i replicate a webrequest with custom parameters (not postdata, not url parameters)?

Context:
Hi everyone, i am trying to simulate a query on this website, but i am failing to do so.
I am using C# and a custom self developed library to Wrap the WebRequests actions making it easier to simulate Posts and Gets for Strings and Bitmaps.
Also, i'm using Fiddler2 Web Debugger to debug the web requests of the service
How to test the service Yourself:
Link to the service
Use this document on the first white box : 04034872000121
Write the captcha and click at "Consultar"
Thats it.
Problem:
After Debuging the requests with fiddler, and replicated everything on code (Cookies, Origin, Host, Postdata with a huge json and so on).
The request for the query, still not working, it redirects me to the home page again, instead of querying the document. (I am allowing "AutoRedirect" on web request object).
The only parameter that i'm not beeing able to replicate is the : GxAjaxRequest: 1
Here is the Fiddler debug feedback of the request:
POST http://sefaznet.ac.gov.br/sefazonline/servlet/hpfsincon?0898a16d81a4e94896958b17b52f252d,gx-no-cache=1354713117196 HTTP/1.1
Host: sefaznet.ac.gov.br
Connection: keep-alive
Content-Length: 1337
Origin: http://sefaznet.ac.gov.br
GxAjaxRequest: 1 **Weird Parameter. I've never saw it before.**
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
Content-Type: application/x-www-form-urlencoded
Accept: */*
Referer: http://sefaznet.ac.gov.br/sefazonline/servlet/hpfsincon
Accept-Encoding: gzip,deflate,sdch
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: GX_SESSION_ID=vSLRLKed3eXJGMBorGepVtQkJOQ1I3o0EBUVzT0g%2BI8%3D; JSESSIONID=af2ba968b7889ec8869caaaba281
vNUMDOC=04034872000121&cfield=chin&BUTTON1=Consultar&BTN_VOLTAR=Retornar&GXState=%7B%22_EventName%22%3A%22E'VISUALIZADADOS'.%22%2C%22_EventGridId%22%3A44%2C%22_EventRowId%22%3Aundefined%2C%22nRC_Duplicados%22%3A%220%22%2C%22CAPTCHA1_Reloadimagetext%22%3A%22Obter%20nova%20imagem!%22%2C%22CAPTCHA1_Validationresult%22%3A1%2C%22GX_FocusControl%22%3A%22vNUMDOC%22%2C%22GX_AJAX_KEY%22%3A%2264FFFF0AFF7A4DFF2655FFFFFF26FF77%22%2C%22AJAX_SECURITY_TOKEN%22%3A%221a9634f566dcd40d12bb8146fd7ff6edca12ae737a3743d79b4b826c3bd4a604%22%2C%22GX_CMP_OBJS%22%3A%7B%7D%2C%22sCallerURL%22%3A%22%2Fsefazonline%2Fservlet%2Fhpfsindado%3FeTlFtl5mBgEOtpLCt8Q02bMjmN3K93hV7i2Uxq_rHv0%3D%22%2C%22GX_RES_PROVIDER%22%3A%22com.genexus.webpanels.GXResourceProvider%22%2C%22GX_THEME%22%3A%22GeneXusX%22%2C%22_MODE%22%3A%22%22%2C%22Mode%22%3A%22%22%2C%22IsModified%22%3A%221%22%2C%22MESSAGE_Width%22%3A%22100%22%2C%22MESSAGE_Height%22%3A%22100%22%2C%22MESSAGE_Show%22%3A%22false%22%2C%22MESSAGE_Title%22%3A%22Title%22%2C%22MESSAGE_Message%22%3A%22This%20is%20the%20message%22%2C%22MESSAGE_Type%22%3A%22alert%22%2C%22MESSAGE_Icon%22%3A%22info%22%2C%22MESSAGE_Cls%22%3A%22%22%2C%22MESSAGE_Position%22%3A%22t%22%2C%22MESSAGE_Duration%22%3A1%2C%22MESSAGE_Visible%22%3A1%2C%22CAPTCHA1_Width%22%3A%22140%22%2C%22CAPTCHA1_Height%22%3A%2239%22%2C%22CAPTCHA1_Visible%22%3A1%7D&
Question:
How do i actually replicate/add this parameter to my webrequest via code ?
Is there any way to do so ?
By the way, the site messes alot with scripts which was hard to "figure out" the origin from most parameters used on the requests.
I hope someone might help me out.
Thanks in advance.
I've figured out.
The problem was that i've had to add a custom header to each request.
webRequest.Headers.Add ("customheadertext and value");
Now fiddler shows correctly my new request, with the added header
POST http://sefaznet.ac.gov.br/sefazonline/servlet/hpfsincon?0898a16d81a4e94896958b17b52f252d,gx-no-cache=1354721123208 HTTP/1.1
GxAjaxRequest: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1
Content-Type: application/x-www-form-urlencoded
Referer: http://sefaznet.ac.gov.br/sefazonline/servlet/hpfsincon
Host: sefaznet.ac.gov.br
Cookie: GX_SESSION_ID=B8w8AQ4W%2FLzLHIpBor3JwJDQAWGy1xRqCYUMnzF14Yk%3D; JSESSIONID=c19564cbebfab1911442fd64a0bb
Content-Length: 1291
Expect: 100-continue
Accept-Encoding: gzip, deflate

Categories