How do I prevent ASP.Net from sending a default charset? - asp.net

I'm working on building some web pages for testing various vulnerability scenarios, but ASP.Net, or IIS, is doing too good a job of protecting me from myself.
One of the things I'm trying to do is return responses with various Content-Type headers, with and without charset declarations. The problem I that if I leave out the charset, then ASP.Net seems to add in utf-8 by default.
In my ASPX.cs code-behind, if I have Response.AddHeader("Content-Type", "text/html") or Page.ContentType = "test/html", I would expect to see the following header returned by the page:
Content-Type: text/html
Instead I get:
Content-Type: text/html; charset=utf-8
If I use Response.AddHeader("Content-Type", "text/html; charset=iso-8859-1") then I get the expected header:
Content-Type: text/html; charset=iso-8859-1
Is there a way to stop ASP.Net (IIS?) from appending charset=utf-8 to the header when I don't want it?
I'm using ASP.Net 4.0 and IIS 7.5.

Try this:
Response.Charset = "";

Related

ASP.NET: Overriding Content-Type Header

I am running a set of ASP.NET pages on IIS 7.5, Windows 2008 R2. I do not have access to the ASP.NET source code.
Each of these pages is emitted with the default Content-Type header:
Content-Type: text/html; charset=utf-8
However, these pages are producing KML and as such should instead be emitting this Content-Type header:
Content-Type: application/vnd.google-earth.kml; charset=utf-8
I tried to override the default Content-Type header in IIS Manager as follows:
Default Web Site => Application Folder => IIS Group => HTTP Reponse Headers => Add:
Add Custom HTTP Response Header
Name: [Content-Type]
Value: [application/vnd.google-earth.kml; charset=utf-8]
After doing so, the Content-Type header was changed but not in a desirable way:
text/html; charset=utf-8,application/vnd.google-earth.kml; charset=utf-8
As you can see, instead of replacing the default Content-Type header, the value I provided was appended to the existing Content-Type header.
Question: Is there some way to override the Content-Type header in IIS Manager? Or, is the only solution to acquire the ASP.NET source and explicitly set the Content-Type header there?

Error pages does not following content type/ format

I followed this tutorial, http://symfony.com/doc/current/cookbook/controller/error_pages.html, and have error.html.twig and error.json.twig within app/Resources/TwigBundle/views/Exception/
Even though the content type of the request is set to application/json, all errors default to the html version of the error page.
The format of the route is also defined:
http://symfonyinstall/api/v1/users.json
Request Header:
Accept: application/json
Content-Type: application/json
Connection: keep-alive
Origin: chrome-extension: //rest-console-id
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.162 Safari/535.19
Response Header:
Status Code: 404
date: Sun, 29 Apr 2012 06:54:35 GMT
Content-Encoding: gzip
X-Powered-By: PHP/5.3.10
Transfer-Encoding: chunked
Connection: keep-alive
Server: nginx
Content-Type: text/html; charset=UTF-8
cache-control: no-cache
I'm out of ideas... and I really need a json version of the errors for my API to work...
I just hit the same problem, and although your question is quite old and symfony bumped a few versions up since then, the problem is still relevant, so even if you don't need to know it any more, maybe somebody else will.
Your original problem was probaly caused by error described here, but there wasn't much going on about it after initial post. Since then the entire codebase was updated, so while the same symptoms reappeared, the error is not related. I am posting it here because anybody looking for an answer these days will probably find this question (as I did :).
Even when returing JsonResponse directly form kernel exception handler, it will still have Content-Type: text/html; charset=UTF-8. This stumped me so much that I used netcat to make a manual request without any smart software in between, and it turns out that the response in such case has actually two different Content-Type headers:
HTTP/1.0 500 Internal Server Error
Connection: close
X-Powered-By: PHP/5.5.9-1ubuntu4.17
Content-Type: text/html; charset=UTF-8
Cache-Control: private, must-revalidate
Content-Type: application/json
pragma: no-cache
expires: -1
X-Debug-Token: 775c55
X-Debug-Token-Link: http://127.0.0.1:8000/_profiler/775c55
Date: Thu, 27 Oct 2016 23:08:31 GMT
Now, double Content-Type header is not something you see everyday. It seems that this is implemented in Symfony\Component\Debug\ExceptionHandler class that is only used in debug mode. In order to be as robust as possible, it first renders standard Symfony error page that describes thrown exception. Rendered content is not sent back directly, instead it leverages PHP's output buffering feature to buffer and store produced output. Then it attempts to produce custom error page from framework. In case this fails, previously prepared message is sent.
Output buffering however works only for message content, and not for headers - these are always sent directly. This problem only appears in debug environment, and unusual content types on error are only common in WebAPI, where debug mode is arguably of little use. This makes exposure surface relatively small, but if an application that offers both WebAPI and end-user interface needs to be tested, this might become a problem.
Solving this problem without modifying internal Symfony files doesn't seem possible. Output control sits deep within symfony kernel and doesn't offer any configuration. Anyway, I am not convinced of benefits of such solution. If anyone could explain to me what could have happened during custom exception handler that would make default handler useless in case it failed?
Maybe user code messing with ob_* functions?

ASMX Web Service using wrong encoding on incoming request

My .NET ASMX webservice is accepting requests from a client I don't have direct control over. It's sending a request that looks like this:
POST /Service.asmx HTTP/1.1
Connection: Keep-Alive
Pragma: no-cache
Content-Length: 1382
Content-Type: text/xml
Accept: text/xml
Host: localhost
User-Agent: Borland SOAP 1.1
SOAPAction: "http://domain.com/InsertRecords"
<?xml version="1.0"?>
<SOAP-ENV:Envelope... <v>ÄLMÅ BÄCK</v></SOAP-ENV:Envelope>
In my WebMethod, the string ÄLMÅ BÄCK gets munged to ??LM?? B??CK -- typical encoding mess-up.
In my testing I've found that if I simply tweak the content-type header, all is well:
Content-Type: text/xml; charset=utf-8
Why is .NET choosing an encoding other than utf-8 when it's unspecified, and is there any way I can coerce this ASMX to use UTF-8 encoding?
The following code run before the web service handler is invoked resulted in the HTTP Request correctly decoded:
if (HttpContext.Current.Request.ContentType == "text/xml") {
HttpContext.Current.Request.ContentType = "text/xml; charset=UTF-8";
}
This feels a bit hacky, but I believe it'll work well for my circumstances. I'm still very interested in some background information on why this was an issue at all, and if there's a better way to pull this off (besides getting the client to be more explicit about the encoding).
IIS 7.5 has configuration options to help with this. (I don't know if earlier versions support this.) I had a similar issue where I have a web application that receives requests from a system that uses the upper 5 characters of the extended ASCII character set as meaningful delimiters. These were getting munged by the decoding that IIS was applying to incoming requests. I found some IIS config options to fix this issue.
First, in IIS Manager, select your website and open the .NET Globalization settings:
There are settings for the expected encodings for File, Requests, Response Headers, and Responses. There are dozens of encoding options to choose from:
This worked perfectly for my scenario because this particular site only received requests from a program that I wrote, so I controlled both ends. With an unknown audience, you're just hoping your users encode their requests appropriately. (But then, that's true even if you use the default encodings...)

IE8: Unable to download file sent through Silverlight and ASP.NET

In our ASP.NET web site we have developed an aspx page that allows the user to download a file. The file path is sent as a parameter and then the file contents are read and written to the response stream. The code that we have used is the following:
string filepath = HttpContext.Current.Request.Params["FilePath"];
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(filepath));
Response.TransmitFile(filepath);
Response.Flush();
Everything works as expected in our development environment, but when we use this piece of code in our production server, we noticed that when trying to download almost all kind of files, nothing happens in the browser. It just opens a new window for that aspx page, but then it gets closed almost inmediately. It is very weird since we have tried downloading .pdf, .doc, .xls, .txt and image files with no luck, except with some (not all) .msg files.
We have being looking for a clue sniffing the HTTP traffic that reach to the browser with Fiddler, but we have seen nothing strange. In all cases the file contents are sent to the browser with no differences, so it seems that it is the browser doesn´t show the open/save/cancel dialog.
Here is a sample of the headers received in the browser with a failing file:
HTTP/1.1 200 OK Proxy-Connection:
Keep-Alive Connection: Keep-Alive
Content-Length: 421395 Via: 1.1
IBISA01 Date: Wed, 26 Jan 2011
12:02:54 GMT Content-Type:
application/octet-stream Server:
Microsoft-IIS/7.5 Cache-Control:
private Content-Disposition:
attachment;filename=P08-0656 Interflex
Especificación Inteface SGA ERP
Version 0.1.pdf X-AspNet-Version:
4.0.30319 X-Powered-By: ASP.NET
And these are the headers of a file that can be downloaded:
HTTP/1.1 200 OK Proxy-Connection:
Keep-Alive Connection: Keep-Alive
Content-Length: 290816 Via: 1.1
IBISA01 Date: Wed, 26 Jan 2011
12:03:29 GMT Content-Type:
application/octet-stream Server:
Microsoft-IIS/7.5 Cache-Control:
private Content-Disposition:
attachment;filename=Acalaracion final
Fichero ascii proveedores
Interflex.msg X-AspNet-Version:
4.0.30319 X-Powered-By: ASP.NET
In all cases, the full contents of the file appear after the headers with apparently no problems related to encoding.
We are wondering if there is some possibility to debug or trace the Internet Explorer activity to see why is rejecting to download the files.
The web server has Windows Server 2008 R2 and IIS 7.5. The browsers that we are using are IE 8.0 over Windows 7.
Many thanks in advance.
Jose Antonio Arroba
We had a similar issue with pdfs, try adding this.
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma", "no-cache");
Edit Actually it's to do with your filenames:
How to encode UTF8 filename for HTTP headers? (Python, Django)
Try removing the ó from the example that doesn't work
Finally we were able to see what was happening with this odd behavior in Internet Explorer when trying to download files. I forgot to mention that we were trying to download the file from a Silverlight app that calls an aspx page in charge of writing the file contents in its response. It seems that the security engine of Internet Explorer treats this behavior as an automatic download, and blocks it by default when browsing from a non intranet server.
Enabling the "Automatic prompting for file downloads" setting in the Internet Explorer Security settings for the Internet zone solved the problem. What still puzzles us is why before enabling this setting we were able to download some of the files.
Thank you very much to all who has tried to help us. Hope that this answer could save time to those who could experience this same bevavior in the future.
Best regards,
Jose Antonio Arroba
Try this for each case...
Dim strExtension as String = ""
Dim strType as String = ""
strExtension = Path.GetExtension(filepath)
Select Case strExtension.ToUpper()
Case ".PDF"
strType = "text/pdf"
Exit Select
CASE ".DOC"
strType = "text/doc"
Exit Select
End Select
Response.Clear()
Response.ClearHeaders()
Response.Buffer = True
Response.ContentType = strType

Exporting rendered HTML page to Word is not working in IE

I have a rendered HTML page that I am exporting to MS Word and downloading on a button click.
Here is the code snippet in the button click.
` Me.EnableViewState = False
Response.ContentType = "application/vnd.ms-word"
Response.AddHeader("Content-Disposition", "attachments;filename=XXXXXXX.doc")
Response.Buffer = True
Response.BufferOutput = True`
The functionality works perfectly well in Firefox & IE when I checked in system testing environment (locally). However when it was moved on to the hosting server (production environment) the functionality is not working in IE but is still working perfectly in Firefox.
I am not sure on where to check for the exact issue. Could it be a caching related problem?
In IE it is just not opening the download window which we will obtain when the rendered HTML content type is changed and the response stream is flushed. No exception is thrown.
I received the following response header:
HTTP/1.0 200 OK
Cache-Control: private
Content-Length: 15189
Content-Type: application/vnd.ms-word;
charset=utf-8 Server: Microsoft-IIS/7.5 X-AspNet-Version: 2.0.50727
Content-Disposition: attachments;filename=NewAccountForm.doc X-Powered-By: ASP.NET
Date: Fri, 18 Mar 2011 10:18:07 GMT X-Cache: MISS from Gateway X-Cache-Lookup: MISS from Gateway:808 Via: 1.0 Gateway (squid/3.0.STABLE10) Proxy-Connection: keep-alive
Is your hosted environment adding http headers? IIS could easily be configured to add headers that are messing up what you want to send out. It's actually quite common, and could be the issue. You'll need to determine this for sure, so here's a suggestion for investigating:
Try using a WebClient class and look at the Response headers.
Edit - updated
I just noticed - did you remember to put
Response.Clear();
before adding headers? It may not be the hosting environment at all. However, given that it works locally and not at your hosting environment, and assming that it is the same code, it still looks to me like something is different about the hosted environment, and the most logical option would be the headers.
I set Response.Charset = "" and always do Response.Flush(), Response.End(), and Response.Close() after I export the HTML.

Resources