How to modify Cache-Control setting in HttpResponse - asp.net-mvc

My ASPNET Zero alway reload all css and js files instead of using cache. That is the reason it was too slow. So how can I change this setting value?

You can add asp-append-version="true" to the script or link tags in the razor pages where your css/js files are included.
Abp does provide dynamic scripts which are created at runtime creation. As such, there are limitations to what you can cache as discussed at https://github.com/aspnetboilerplate/aspnetboilerplate/issues/3673

I have found the reason, the ASPNET Zero disable Client cache by default. My solution is just commented a line of code as below
protected override void Application_BeginRequest(object sender, EventArgs e)
{
base.Application_BeginRequest(sender, e);
//DisableClientCache();
}
private void DisableClientCache()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(CacheExpireDate);
Response.Cache.SetNoStore();
}

Related

Application.EndRequest, MVC and .htm files

I have the following code in my Global.asax:
void Application_EndRequest(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
HttpContext context = application.Context;
string path = context.Request.Path;
string contentType = context.Response.ContentType;
System.Diagnostics.Debug.WriteLine("-----------------------------------");
System.Diagnostics.Debug.WriteLine("Path: " + path);
System.Diagnostics.Debug.WriteLine("ContentType:" + contentType);
}
I have a Help folder at the root of the site (~/Help) that contains static .htm files. I notice that not all of these files are being run through EndRequest. Sometimes I see assets in the page being logged (e.g. .js files) but not the htm file itself. Sometimes they do get logged.
Why don't all of these files run through EndRequest and how can I ensure that they do?
In the end my configuration is like this:
AppPool pipeline: Integrated
RouteExistingFiles: false (default)
runAllManagedModulesForAllRequests: true
All of this was how it was when I wrote up this question. The thing I did different was to go into my web.config and manually add a handler under <httpHandlers>:
<add verb="GET,HEAD,POST,DEBUG" path="*.htm" type="System.Web.UI.PageHandlerFactory" />
One thing that was throwing me off was that once the file had come down the browser was caching it and not re-requesting it (until I cleared the cache).

MVC 5 prevents access to content via Iframe

Ever since the upgrade from MVC4 to MVC5, I have noticed an extra server header added to my web pages:
X-Frame-Options: SAMEORIGIN
I understand security benefits of adding this tag, but one of the pages is meant to be included inside an iframe from other projects (on other domains), this extra header is preventing this.
I have verified it is not the hosting IIS7 server that is adding the header, and when I downgraded back to MVC4 - the header is gone.
Does anyone know how to remove this default from MVC5?
MVC5 automatically adds the HTTP header X-Frame-Options with SAMEORIGIN. This prevents your site from being loaded into an iframe.
But we can turn this off in Application_Start in the Global.asax.cs.
Example
protected void Application_Start()
{
AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
}
Update
I have written a post about this MVC5 prevents your website being loaded in an IFRAME
Try something like this in Global.asax:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("X-Frame-Options");
}
EDIT:
Look at answer of Colin Bacon. It is more correct than mine.
In short - don't remove this header if you don't want to run your site in IFRAME because it will open forgery vulnerability. But if you still want to remove it - use AntiForgeryConfig.SuppressXFrameOptionsHeader = true; in Application_Start, it is more cleaner way for doing this.
If you want a little more flexibility, here's an ActionAttribute that adds/removes headers based on a whitelist. If the referrer isn't in the whitelist, then the SAMEORIGIN header is left in place. I was going to paste the code, but SO complains about the length.
https://long2know.com/2016/06/asp-net-anti-forgery-xframe-options/
Personally, I don't think it's a good idea to disable the X-Frame-Options across the whole site.I've created an ASP.NET MVC filter which removes this header and I simply apply this filter to the portions of the site that are used in iFrames e.g. widgets.
public class AllowDifferentOrigin : ActionFilterAttribute, IActionFilter
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
filterContext.HttpContext.Response.Headers.Remove("X-Frame-Options");
base.OnResultExecuted(filterContext);
}
}
Here is a replacement Extension method for the HtmlHelper class. It will first clear all X-Frame-Options headers and then add back a single X-Frame-Options header normally added by the built-in AntiForgeryToken method.
This technique respects the SuppressXFrameOptionsHeader setting, but has the downside of removing all previously added X-Frame-Options headers, even those with values other than SAMEORIGIN.
public static MvcHtmlString AntiForgeryTokenSingleHeader(this HtmlHelper html)
{
string token = AntiForgery.GetHtml().ToString();
HttpResponseBase httpResponse = html.ViewContext.HttpContext.Response;
httpResponse.Headers.Remove("X-Frame-Options");
if (!AntiForgeryConfig.SuppressXFrameOptionsHeader)
{
httpResponse.AddHeader("X-Frame-Options", "SAMEORIGIN");
}
return new MvcHtmlString(token);
}

How to keep sitemap.xml out of webapp's deploy folder?

I'm using glassfish server 3.1.2 and jsf 2.1. Based on sitemaps.org standarts, sitemap file of entire web site should be in root folder. I will have multiple sitemaps and sitemap will change dynamically after i create new entries. I have read there, i want to use alternate docroot. But i can't create alternate docroot for root directory. I should find a solution as like as alternate docroot.
You could create a simple servlet to perform the job.
#WebServlet("/sitemap.xml")
public class SitemapServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/xml");
// You might want to add finer grained browser cache related headers.
InputStream input = new FileInputStream("/some/path/to/sitemap.xml");
OutputStream output = response.getOutputStream();
// Now just write input to output using your favorite way.
// ...
}
}

How can I add a custom parameter to an Umbraco template

I need a way how to add an custom html header in Umbraco. Ideally the value of this custom field can be modified by having an extra textbox in the page editor for that page (Similar to page title box).
Is this possible to do?
Do you mean you want to add HTTP headers via code-behind?
Assuming you've already created your textstring property on the document type in question, you have to be able to access the property from code-behind or inline code and then add the HTTP header, also from code-behind.
The quickest way to add C# code to the template is to do inline code, e.g.
<script runat="server">
protected void Page_Init(object sender, EventArgs e)
{
}
</script>
Alternatively, you can add code-behind files to your template (more info)
Now that you can run server code, you can access the doc type property and create the HTML header.
umbraco.NodeFactory.Node currentNode = umbraco.NodeFactory.Node.GetCurrent();
umbraco.interfaces.IProperty httpHeader = currentNode.GetProperty("httpHeaderAlias");
And of course, finally add the HTTP header
Response.AddHeader("HeaderName", httpHeader.Value);
All together now, add this to your template (masterpage aspx):
<script runat="server">
protected void Page_Init(object sender, EventArgs e)
{
umbraco.NodeFactory.Node currentNode = umbraco.NodeFactory.Node.GetCurrent();
umbraco.interfaces.IProperty httpHeader = currentNode.GetProperty("httpHeaderAlias");
Response.AddHeader("HeaderName", httpHeader.Value);
}
</script>
(Note: Code is for Umbraco 4.7)

Implementing a WAP site using ASP.NET-MVC

We plan on implementing a WAP site using ASP.NET-MVC.
Has anyone any experiance of this? Are there any Gotchas?
We will also be implementing a "standard" web site for browsers. Would it be possible to have a single set of Models and Controllers, and just have seperate views for each site?
It is possible to have for the most part a single set of models and controllers.
The way to do it will be via implementing the following Theming/Templating engine.
[Theming Support][1]
I piggy backed my solution on top of a Theming/Templating engine.
The major deviation from the article source is in the Global.asax.cs file where you need to add the following lines of code:
protected void Application_BeginRequest(Object Sender, EventArgs e)
{
SetTheme();
}
//this will set the responses Content Type to xhtml and is necessary as C# sends the WML response header
protected void Application_PreSendRequestHeaders(Object Sender, EventArgs e)
{
if (this.Context.Items["themeName"].ToString() == "xhtml")
{
this.Context.Response.ContentType = "application/vnd.wap.xhtml+xml";
}
}
private void SetTheme()
{
//set the content type for the ViewEngine to utilize.
HttpContext context = this.Context;
MobileCapabilities currentCapabilities = (MobileCapabilities)context.Request.Browser;
String prefMime = currentCapabilities.PreferredRenderingMime;
string accept = context.Request.ServerVariables["HTTP_ACCEPT"];
context.Items.Remove("theme");
context.Items.Remove("themeName");
if (accept.Contains("application/vnd.wap.xhtml+xml"))
{
context.Items.Add("themeName", "xhtml");
}
else if (prefMime == "text/vnd.wap.wml")
{
context.Items.Add("themeName", "WAP");
}
if (!context.Items.Contains("themeName"))
{
context.Items.Add("themeName", "Default");
}
}
I know I had to make a couple of code changes to make it MVC 1 compatible, but I can't remember the exact changes.
The other major problem I had was debugging the output. For this I used firefox with an extension ([User Agent Switcher][2]) that I've changed to add Accept Types to it.
For WAP2/XHTML1.2 the Accept Types are: text/html,application/vnd.wap.xhtml+xml,application/xhtml+xml,application/xml;q=0.9,/;q=0.8
Obviously you need your masterpage and content pages to adhere to WML or XHTML1.2
[1]: http://frugalcoder.us/post/2008/11/13/ASPNet-MVC-Theming.aspx Theming Support
[2]: http://chrispederick.com/work/user-agent-switcher/ User Agent Switcher

Resources