IIS7 overwriting defined HTTP header values - asp.net

I am attempting to set the content-type of an asp.net .ashx file to text/plain.
When I run this through the ASP.NET Development Server, the content-type is properly set. When I serve it through IIS7, however, the content-type (and any other header values I set) don't come through (it came through as text/html).
The only value set in the HTTP Response Headers section of IIS Manager is the X-Powered-By attribute. I tried setting the content-type here, but that didn't work. But if I removed the X-Powered-By attribute, it was removed from the header.
Any ideas?
Code in .ashx file
public class Queries1 : IHttpHandler, System.Web.SessionState.IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("hello");
}
public bool IsReusable
{
get { return false; }
}
}
HTTP Header from IIS7 (pulled through python script):
[('content-length', '58'),
('x-powered-by', 'ASP.NET'),
('server', 'Microsoft-IIS/7.0'),
('date', 'Thu, 21 Oct 2010 15:51:28 GMT'),
('content-type', 'text/html'),
('www-authenticate', 'Negotiate, NTLM')]

To add HTTP Headers you need to use:
context.Response.Headers.Add("MyHeader", "Hello World!");
Based on Coding Gorilla's clarification, are you sure you're browsing to the correct url? If I try the exact same code as you've written I see the following in Fiddler:
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Vary: Accept-Encoding
Server: Microsoft-IIS/7.5
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
Date: Thu, 21 Oct 2010 20:11:44 GMT
Content-Length: 5
hello

Related

Access-Control-Allow-Origin header completely ignored by FireFox

I set up my website (running IIS8.5) to send the response header for CORS to a subdomain off my main domain and the header response is getting to Firefox just fine. All plug-ins, ad-blockers, etc, are disabled and I can see the header in the DOM inspector.
I've tried:
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: https://services.mywebsite.com
Access-Control-Allow-Origin: http://services.mywebsite.com
Access-Control-Allow-Origin: null
Access-Control-Allow-Origin: "null"
I've verified the SSL Certificate is working just fine (it's a wildcard cert for *.mywebsite.com from Sectigo and I've verified that the entire certification path is working properly)
There are no other response headers except for: X-Frame-Options: SAMEORIGIN ,however, I removed it with the same result.
The site predates CORS by years (ASP.NET Webforms) and there are no other settings I can find that would prevent Firefox from acknowledging this response header.
I've read dozens of posts here (usually someone had a self-signed cert or forgot something) but am at a loss on what is wrong?
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://services.mywebsite.com/api/geodata/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
It's absolutely NOT MISSING! WTF Firefox?
Pulling hair out here. Anyone?
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
Expires: -1
Server: Microsoft-IIS/8.5
X-Content-Type-Options: nosniff
Access-Control-Allow-Origin: https://services.mywebsite.com
X-Frame-Options: SAMEORIGIN
Date: Wed, 27 May 2020 08:28:05 GMT
Someone else suggested adding a CORS module to IIS. I did, then added to my web.config file the following (in system.webserver section):
<cors enabled="true">
<add origin="*" allowed="true" >
<allowHeaders allowAllRequestedHeaders="true" />
</add>
</cors>
No Joy! Same message from Firefox (and Chrome) - both browsers completely ignore this directive. Could this be a bug in Mozilla?
-------------------- more info ---------------------------------
I think the problem is with the following jquery script with my CHAT (which is doing the calling to the api). It's worked for 12 years (and still works on old versions), so I'm looking to see what's been deprecated. I suspect that SignalR may be the issue and confusing the browser(s) - since SignalR is making the request (not sure, though -just guessing now). Sorry for not mentioning this sooner.
$.connection.hub.start()
.done(function () {
var existingChatId = getExistingChatId(chatKey);
$.get("https://services.mywebsite.com/api/geodata/", function (response) {
myHub.server.logVisit(document.location.href, document.referrer, response.city_name, response.region_name, response.country_name, existingChatId);
}, "json");
})
.fail(function () { chatRefreshState(false); });
------------------- after using wildcards for CORS headers --------------
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Transfer-Encoding: chunked
Content-Type: application/json; charset=UTF-8
Expires: -1
Server: Microsoft-IIS/10.0
X-Content-Type-Options: nosniff
X-SourceFiles: =?UTF-8?B?RDpcU2l0ZXNcaWNhcnBldGlsZXMyXFdlYlxzaWduYWxyXHN0YXJ0?=
X-Powered-By: ASP.NET
X-Frame-Options: SAMEORIGIN
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: *
Date: Sun, 07 Jun 2020 10:31:35 GMT
Still no joy - Headers are there. Must be a bug in ASP.NET webforms, IIS, SignalR (please note this is NOT MVC). Time to upgrade this site for this client. No one supports webforms anymore, anyway - it's dead.
It's not possible to do cross domain requests with SignalR and be CORS compatible. There is no way around this problem.
Just move your service to your www.yourwebsite.com and save your hair!
You can install cors dependency:
"Microsoft.AspNet.Cors": "6.0.0-rc1-final"
Add the CORS services in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
}
And enable it for specific domain:
public void Configure(IApplicationBuilder app)
{
app.UseCors(builder =>
builder.WithOrigins("http://example.com"));
}
Another option is enable cors for a specific method:
public class HomeController : Controller
{
[EnableCors("AllowSpecificOrigin")]
public IActionResult Index()
{
return View();
}
}
Or enable it for an specific controller:
[EnableCors("AllowSpecificOrigin")]
public class HomeController : Controller
{
}
If you're using MVC 3, and you have the file Global.asax you can use the method:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", allowedOrigin);
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
}
If you're using WebApi, you might use:
Install-Package Microsoft.AspNet.WebApi.Cors
And register the cors using:
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
}
And:
[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
// My methods...
}
Or enable it for whole the project:
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("http://example.com", "*", "*");
config.EnableCors(corsAttr);
}
ASP.Net web forms
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Also try:
Response.AppendHeader("Access-Control-Allow-Methods","*");
Try adding directly in web config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
Do you have app.UseCors() in your middleware pipeline, before app.MapSignalR()?
You can start with app.UseCors(CorsOptions.AllowAll) to check if it'll work and then add your own domain.
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();

How to set Response.Cache.SetCacheability in ASP.net WebForms?

How do i call Response.Cache.SetCacheability in WebForms?
If you look at MSDN's How to: Set a Page's Cacheability Programmatically:
To set a page's cacheability programmatically
In the page's code, call the SetCacheability method on the Cache property of the Response object.
The following code sets the Cache-Control HTTP header to Public.
Response.Cache.SetCacheability(HttpCacheability.Public);
Fine. Excellent. Good. Except how do i do it?
In try adding it to the Page_Init event handler:
protected void Page_Init(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.Public); //Public, while we test this
}
But the response from the server does is not public (and in fact is private):
HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Fri, 11 Jul 2014 14:11:06 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 9382
Connection: Close
So i want to confirm that my code is working, so i add some dummy headers:
protected void Page_Init(object sender, EventArgs e)
{
//Response.Headers.Add("X-Hello-Before", "WhyArentYouWorking");
Response.AddHeader("X-Hello-Before", "WhyArentYouWorking");
Response.Cache.SetCacheability(HttpCacheability.Public); //Client is allowed to cache
//Response.Headers.Add("X-Hello-After", "MyGodYouSuck");
Response.AddHeader("X-Hello-After", "MyGodYouSuck");
}
and the items appear in the response header:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/11.0.0.0
Date: Fri, 11 Jul 2014 14:16:47 GMT
X-AspNet-Version: 4.0.30319
X-Hello-Before: WhyArentYouWorking
X-Hello-After: MyGodYouSuck
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Length: 9382
Connection: Close
The question is:
How do i make ASP.net do what i tell it to do?
I don't know where the bug is. It could be in ASP.net. It could be in WebForms. It could be in .NET Framework 4.0. It could be in Cassini.
Do you have a proxy in between, maybe that is not letting you change it? Otherwise you can try to set it IIS as well:
Open your IIS Manager, go to your application in the tree.
Select your application and in the right hand section Double click "HTTP Respond Headers" option.
Click "Add…" on the Actions Panel
Fill in the pop-up window:
Name: Cache-Control
Value: public
and see if that works.

MVC 3 client caching

I am trying to make modifications to an existing CDN. What I am trying to do is create a short cache time and use conditional GETs to see if the file has been updated.
I am tearing my hair out because even though I am setting a last modified date and seeing it in the response headers, on subsequent get requests I am not seeing an If-Modified-Since header being returned. At first I thought it was my local development environment or the fact that I was using Fiddler as a proxy for testing so I deployed to a QA server. But what I am seeing in Firebug is so different than what I am doing. I see the last modified date, for some reason it is setting my cache-control to private, and I have cleared any header Output Caching and the only header IIS 7.5 is set to write is to enable Http keep-alive, so all the caching should be driven by the code.
This seemed like such a no-brainer, yet I've been adding and removing headers all day with no luck. I checked global.asax and anywhere else (I didn't write the app so I was looking for any hidden surprises and am stumped. Below is the current code and request and response headers. I have the expiration set to 30 seconds just for testing purposes. I have looked at several samples, I don't see myself doing anything different, but it simply won't work.
Response Headersview source
Cache-Control private, max-age=30
Content-Length 597353
Content-Type image/jpg
Date Tue, 03 Sep 2013 21:33:55 GMT
Expires Tue, 03 Sep 2013 21:34:25 GMT
Last-Modified Tue, 03 Sep 2013 21:33:55 GMT
Server Microsoft-IIS/7.5
X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 3.0
X-Powered-By ASP.NET
Request Headersview source
Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection keep-alive
Cookie __utma=1.759556114.1354835397.1377631052.1377732484.36; __utmz=1.1354835397.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)
Host hqat4app1
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetLastModified(DateTime.Now);
return new FileContentResult(fileContents, contentType);
The relevant code is:
public ActionResult Resize(int id, int size, bool grayscale)
{
_logger.Debug(() => string.Format("Resize {0} {1} {2}", id, size, grayscale));
string imageFileName = null;
if (id > 0)
using (new UnitOfWorkScope())
imageFileName = RepositoryFactory.CreateReadOnly<Image>().Where(o => o.Id == id).Select(o => o.FileName).SingleOrDefault();
CacheImageSize(id, size);
if (!ImageWasModified(imageFileName))
{
Response.Cache.SetExpires(DateTime.Now.AddSeconds(30));
Response.StatusCode = (int)HttpStatusCode.NotModified;
Response.Status = "304 Not Modified";
return new HttpStatusCodeResult((int)HttpStatusCode.NotModified, "Not-Modified");
}
byte[] fileContents;
if (ShouldReturnDefaultImage(imageFileName))
fileContents = GetDefaultImageContents(size, grayscale);
else
{
bool foundImageFile;
fileContents = GetImageContents(id, size, grayscale, imageFileName, out foundImageFile);
if (!foundImageFile)
{
// No file found, clear cache, disable output cache
//ClearOutputAndRuntimeCacheForImage(id, grayscale);
//Response.DisableKernelCache();
}
}
string contentType = GetBestContentType(imageFileName);
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetLastModified(DateTime.Now);
return new FileContentResult(fileContents, contentType);
}
private bool ImageWasModified(string fileName)
{
bool foundImageFile;
string filePath = GetFileOrDefaultPath(fileName, out foundImageFile);
if (foundImageFile)
{
string header = Request.Headers["If-Modified-Since"];
if(!string.IsNullOrEmpty(header))
{
DateTime isModifiedSince;
if (DateTime.TryParse(header, out isModifiedSince))
{
return isModifiedSince < System.IO.File.GetLastWriteTime(filePath);
}
}
}
return true;
}

HttpClient request to local IIS 8.0 does not produce expected headers in the response

I'm making the following request to a local website running in IIS
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.RequestUri = new Uri("http://localhost:8081/");
httpRequestMessage.Method = HttpMethod.Get;
var response = new HttpClient().SendAsync(httpRequestMessage).Result;
This produces the following response headers:
HTTP/1.1 200 OK
Accept-Ranges: bytes
Date: Mon, 03 Jun 2013 22:34:25 GMT
ETag: "50c7472eb342ce1:0"
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
An identical request made via Fiddler produces the following response headers (I've highlighted the differences):
HTTP/1.1 200 OK
Content-Type: text/html
Last-Modified: Fri, 26 Apr 2013 19:20:58 GMT
Accept-Ranges: bytes
ETag: "50c7472eb342ce1:0"
Server: Microsoft-IIS/8.0
X-Powered-By: ASP.NET
Date: Mon, 03 Jun 2013 22:29:34 GMT
Content-Length: 10
Why is there a difference in response headers?
Am I using HttpClient correctly (aside from the fact I am calling Send synchronously)?
TL;DR;
To access all response headers you need to read both HttpResponseMessage.Headers and HttpResponseMessage.Content.Headers properties.
Long(er) answer:
This, basically:
var response = new HttpClient().GetAsync("http://uri/").Result;
var allHeaders = response.Headers.Union(response.Content.Headers);
foreach (var header in allHeaders)
{
// do stuff
}
I see two issues with this:
The Headers property is not appropriately named: it should really be SomeHeaders or AllHeadersExceptContentHeaders. (I mean, really, when you see a property named Headers, do you expect it to return all headers or some headers? I am pretty sure they are in violation of their own framework design guidelines on this one.)
The MSDN page does not mention at any point the fact this is a subset of all headers and developers should also inspect Content.Headers.

OutputCache is sending wrong Vary header when the call hits the cache

I have an action method that I want to cache:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Any, VaryByCustom="index")]
public ActionResult Index()
{
return View();
}
With this approach:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
context.Response.Cache.SetOmitVaryStar(true);
context.Response.Cache.VaryByHeaders["Cookie"] = true;
if (User.Identity.IsAuthenticated)
{
Debug.Print("Authenticated");
context.Response.Cache.SetNoServerCaching();
context.Response.Cache.SetCacheability(HttpCacheability.Private);
return null;
}
else
{
Debug.Print("Non authenticated");
return custom;
}
}
The idea was to keep a cached version of the page for non-authenticated users, but avoid caching for authenticated ones.
I thought it will always return a Vary:Cookie HTTP header, but it is not.
Doing a test with Fiddler and issuing twice the same request, in the first HTTP call it goes good:
HTTP/1.1 200 OK
Cache-Control: public, max-age=300
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 10:53:36 GMT
Last-Modified: Thu, 09 Feb 2012 10:48:36 GMT
Vary: Cookie
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 10:48:37 GMT
Content-Length: 441
But in the second one, it overwrites the header:
HTTP/1.1 200 OK
Cache-Control: public, max-age=297
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 10:53:36 GMT
Last-Modified: Thu, 09 Feb 2012 10:48:36 GMT
Vary: *
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 10:48:39 GMT
Content-Length: 441
So, as far as I know, browsers won't cache the request even if it is public, since Vary:* means that the request has been generated with parameters that are not in the URL nor in the HTTP headers. Is there a way to fix this?
Regards.
UPDATE:
In a similar way, when I send two identical authenticated requests, the first call gets the private modifier, but not the Vary header:
HTTP/1.1 200 OK
Cache-Control: private, max-age=300
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 12:43:14 GMT
Last-Modified: Thu, 09 Feb 2012 12:38:14 GMT
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 12:38:14 GMT
Content-Length: 443
But the second one gets the same response that a non-authenticated request:
HTTP/1.1 200 OK
Cache-Control: public, max-age=298
Content-Type: text/html; charset=utf-8
Expires: Thu, 09 Feb 2012 12:44:32 GMT
Last-Modified: Thu, 09 Feb 2012 12:39:32 GMT
Vary: *
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 3.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Thu, 09 Feb 2012 12:39:33 GMT
Content-Length: 443
I have uploaded a test project showing the issue so may be you want to give it a try.
Please be aware that there is an IHttpModule that sets a request as authenticated or not depending on if the request has a cookie or not, this is not a "real life" approach, it is just for testing purposes.
The project contains only a web page with a link to itself, a link that logs you in, and another link that logs you out:
LogIn : Sends a cookie in a HTTP 302 redirection to the home page again.
LogOut: Sends a expired cookie in a HTTP 302 recirection to the home page again.
The expected/ideal behaviour would be:
User access Index, and get the page from the server. The page show date "A".
User access Index again, and the browser shows the cached version.The page show date "A".
Clean browser cache.
User access Index again, and the browser shows the server cached version. The page show date "A".
User clicks login, and the broswer gets a new page, that show date "B".
User clicks logout, and the browser gets the server cached page. The page show date "A" again.
But this is the behaviour so far:
User access Index, and get the page from the server. The page show date "A".
User access Index again, and the browser shows the cached version.The page show date "A".
Clean browser cache.
User access Index again, and the browser shows the server cached version. The page show date "A".
User clicks login, and the broswer gets a new page, that show date "B".
User clicks logout, and the browser should get the server cached page, but it does not. The page show date "B" again from the browser cache. This is because the lack of the Vary header in the authenticated response.
I don't know if I get something wrong about caching, just missing some detail or the OutputCache does not work very well, but I would appreciate any guidance.
Cheers.
UPDATE 2:
My intention is to use the HTTP cache semantics to:
Allow browsers and proxys to cache the "public" version of the page.
Allow browsers to cache the "authenticated" version of the page for its user.
If I change the OutputCache declaration to do the caching only on the server and prevent the downstream and client caching:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Server, VaryByCustom="index")]
it behaves as expected, but the downstream and client cache is prevented, and that is not what I want.
I don't think the [OutputCache] attribute is what you want, the VaryByCustom method is basically saying that I want to cache different versions based on these parameters, it doesn't really have an option for Do Not Cache and the majority of the code in the attribute is built around server based caching.
That being said the documentation on MSDN for custom caching seems to indicate you need to return a string to vary on based on the authentication state:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if(custom == "user") return "User:" + context.Request.User.Identity.Name;
return base.GetVaryByCustomString(context, custom);
}
And then use the user literal in the VaryByCustom:
[OutputCache(Duration=60*5, Location=OutputCacheLocation.Any, VaryByCustom="user")]
public ActionResult Index()
{
return View();
}
So basically this would result in a cache being built for anonymous (assuming the anonymous identity is empty string or something) and every user on the server, and a Vary: * sent to the client I believe. Obviously not ideal what you are looking for.
If you really just want to cache the unauthenticated version using HTTP caching I would recommend not using the OutputCacheAttribute and using something more custom.
You could easily just write in your own custom attribute something like what you have for your GetVaryByCustomString implementation (this is just some pseudo code, would need more than this):
public class HttpCacheUnauthenticatedAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if(!filterContext.HttpContext.Request.IsAuthenticated) {
//TODO: set unauthenticated caching values and vary here
}
}
}
And then tag your action method with it:
[HttpCacheUnauthenticated]
public ActionResult Index()
{
return View();
}
Sort of wrestling with something similar myself. Have you tried in the web.config to the setting omitVaryStar=true
https://msdn.microsoft.com/en-us/library/ms228124(v=vs.100).aspx
I am using a custom cache provider and in this case there is a simple solution for this.
On the BeginRequest, based on the user authentication status, we set a context information to not run cache:
HttpContext.Current.Items["NoCache"] = "1";
And then on our GetVaryBy method we return null if this information is set:
public override string GetVaryByCustomString(HttpContext context, string custom)
{
if (HttpContext.Current.Items["NoCache"] != null)
return null;
// remaining code here
}
And then on the cache methods, we can test the same. For instance:
public override object Add(string key, object entry, DateTime utcExpiry)
{
if (HttpContext.Current.Items["NoCache"] != null)
return null;
// remaining code here
}

Resources