MiniProfiler does not load - asp.net-mvc

I installed Nuget package miniprofiler.com but the profiler windows is not visible, but the miniprofiler script was generated to the html.
I putted following script to the global.asax
protected void Application_BeginRequest()
{
if (Request.IsLocal)
{
MiniProfiler.Start();
}
}
protected void Application_EndRequest()
{
MiniProfiler.Stop();
}
To the _Layout.cshtml at first line
#using StackExchange.Profiling;
last lines
#MiniProfiler.RenderIncludes()
</body>
</html>
script generated
<script async type="text/javascript" id="mini-profiler" src="/mini-profiler-resources/includes.js?v=ySF6M98CBehTtL86BbiEmys9yxR1HKazhe2sznfdUWQ=" data-version="ySF6M98CBehTtL86BbiEmys9yxR1HKazhe2sznfdUWQ=" data-path="/mini-profiler-resources/" data-current-id="d011005d-606a-4dca-a3a0-8e8654c344af" data-ids="74098d83-5d5f-4f2b-a3ab-1a7294dd4490,f6e7117a-81cf-4632-b30b-9f93ec0ebfbf,b0069a2b-68b3-4e58-a477-5529e780266c,d011005d-606a-4dca-a3a0-8e8654c344af" data-position="left" data-trivial="false" data-children="false" data-max-traces="15" data-controls="false" data-authorized="true" data-toggle-shortcut="Alt+P" data-start-hidden="false" data-trivial-milliseconds="2"></script>
but I do not see the profiler window, what am I doing wrong ?!
I also tried totally new web project (mvc4) in visual studio and the problem is same.

I tried the exact steps as yours and the profiler window was not getting displayed.
I had to add a tag in the web.config file to get the profiler window to appear.
Use runAllManagedModulesForAllRequests="true" as shown below,
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
</modules>
</system.webServer>

Related

Why is 404 Custom Error working but 500 Custom Error not?

I have implemented CustomErrors in my web.config. The 404 error works as intended, the 500 errors simply show an empty default layout page with the standard generated .NET HTML output in the RenderBody area.
The code in the web.config is:
<customErrors mode="On">
<error statusCode="404" redirect="~/404.html"/>
<error statusCode="500" redirect="~/500.html"/>
</customErrors>
404 can be seen here: http://www.airportcars-gatwick.com/i-do-not-exist
500 can be seen here: https://taxis.gatwickairport.com/Book?Q=9fa5-514e-4c3a-972f8baee58fa2b9
(Both files are in place on the server at the same root location)
This is the layout page with HTML injected into the RenderBody
</div>
</header>
<!-- //Header -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
</head>
<body>
<hgroup>
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
</hgroup>
</body>
</html>
<!-- Footer -->
<footer class="footer teal" role="contentinfo">
<div class="wrap">
..etc...
Not sure what I'm missing?
It appears the issue was with a default configuration of my GlobalFilters.
GlobalFilters is a way to associate an attribute with every Action method in the ASP.NET MVC application. I guess my project had automatically taken care of that for me.
Within my app_start folder within the FilterConfig.cs file:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
So by commenting out the RegisterGlobalFilters line in the Global.asax.cs file, the issue was resolved.
protected void Application_Start()
{
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); // Comment out
Hope this helps if anyone else experiences the same behaviour.

Why might I not be getting any results from MiniProfiler?

I can't seem to get any results from MiniProfiler.
I can see the XHR POST to /mini-profiler-resources/results returning a 404. The chrome request inspector gives me a standard server 404 page.
A GET on the same URL also returns a 404, but there is a message saying that "no results were found for the specified id" (I did add the id in the querystring).
When I look at /mini-profiler-resources/results-index it just gives me an empty table with the field headings in - name, started, sql, duration, etc.
I've tried a few things - details below - at this stage I am at a loss as to what I can try next. Any pointers or suggestions for debugging this problem would be much appreciated.
Installed Packages:
MiniProfiler (v3.2.0.157)
MiniProfiler.EF6 (v3.0.11)
MiniProfiler.MVC4 (v3.0.11)
Where MVC4 also caters for MVC5. Which this project is.
Relevant Code:
protected void Application_Start()
{
MiniProfilerEF6.Initialize();
MiniProfiler.Settings.Results_List_Authorize = IsUserAllowedToSeeMiniProfilerUI;
MiniProfiler.Settings.MaxJsonResponseSize = int.MaxValue;
Database.SetInitializer<ApplicationDbContext>(null);
GlobalFilters.Filters.Add(new ProfilingActionFilter());
var copy = ViewEngines.Engines.ToList();
ViewEngines.Engines.Clear();
foreach (var item in copy)
{
ViewEngines.Engines.Add(new ProfilingViewEngine(item));
}
}
protected void Application_BeginRequest(Object source, EventArgs e)
{
if (Request.IsLocal)
{
// this IS being hit
MiniProfiler.Start();
}
}
protected void Applicaton_EndRequest()
{
MiniProfiler.Stop(discardResults: false);
}
private bool IsUserAllowedToSeeMiniProfilerUI(HttpRequest httpRequest)
{
return true;
}
In HomeController.cs:
[AllowAnonymous]
public ActionResult Index()
{
var profiler = MiniProfiler.Current;
using (profiler.Step("Doing complex stuff"))
{
using (profiler.Step("Step A"))
{
ViewBag.Title = "Home Page";
}
using (profiler.Step("Step B"))
{
Thread.Sleep(250);
}
}
return View();
}
And in MasterLayout.cshtml:
#using StackExchange.Profiling;
...
#MiniProfiler.RenderIncludes()
I've Tried:
I have set discardResults to false, like this:
protected void Applicaton_EndRequest()
{
MiniProfiler.Stop(discardResults: false);
}
I can confirm that MiniProfiler.Start() IS getting hit when the page loads.
I can also confirm that the mini-profiler-resources/ route IS being found (using Haack's Route Debugger)
I have the following item in the <handlers> section of web.config, and it is in the correct section (e.g. this guy mistakenly put it in the ELMAH config ).
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
I have set all my output caching to 1 second.
I was using a custom applicationhost.config file to test on a custom url.
I tried removing the custom url bindings and just using the standard localhost:51347.
I also tried putting the snippet below into applicationhost.config instead of the standard web.config.
<add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" />
In applicationhost.config I tried changing
<section name="handlers" overrideModeDefault="Deny" />
to
<section name="handlers" overrideModeDefault="Allow" />
I've added the following into application_start:
MiniProfiler.Settings.MaxJsonResponseSize = int.MaxValue;
As recommended in this answer, I have tried uninstalling all related packages and reinstalling them in this order:
MiniProfiler
MiniProfiler.MVC4
MiniProfiler.EF6
Update
9 days on, the bounty expired and still no joy :(
If anybody reading this in the future has ideas / suggestions, I'd really like to hear them. MiniProfiler is such a great tool and I'm disappointed that I haven't been able to get it working on this occasion.
If I do find the answer myself, I'll post it.
After running into the same issue I found the answer here which worked fine.
http://www.mukeshkumar.net/articles/mvc/performance-test-with-miniprofiler-in-asp-net-mvc
If you get an error after running application with MiniProfiler.Mvc4 or MiniProfiler.Mvc3 which state “/mini-profiler-resources/includes.js 404 not found” then simply add the following line of code in Web.Config inside web server section.
<system.webServer>
<handlers>
<add name="MiniProfiler" path="mini-profiler-resources/*"
verb="*" type="System.Web.Routing.UrlRoutingModule"
resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
</system.webServer>

temporarily Stop Bundling and minification [duplicate]

I have debug="true" in both my web.config(s), and I just don't want my bundles minified, but nothing I do seems to disable it. I've tried enableoptimisations=false, here is my code:
//Javascript
bundles.Add(new ScriptBundle("~/bundles/MainJS")
.Include("~/Scripts/regular/lib/mvc/jquery.validate.unobtrusive.js*")
.Include("~/Scripts/regular/lib/mvc/jquery.validate*")
.Include("~/Scripts/regular/lib/bootstrap.js")
.IncludeDirectory("~/Scripts/regular/modules", "*.js", true)
.IncludeDirectory("~/Scripts/regular/pages", "*.js", true)
.IncludeDirectory("~/Scripts/regular/misc", "*.js", true));
//CSS
bundles.Add(new StyleBundle("~/bundles/MainCSS")
.Include("~/Content/css/regular/lib/bootstrap.css*")
.IncludeDirectory("~/Content/css/regular/modules", "*.css", true)
.IncludeDirectory("~/Content/css/regular/pages", "*.css", true))
Conditional compilation directives are your friend:
#if DEBUG
var jsBundle = new Bundle("~/Scripts/js");
#else
var jsBundle = new ScriptBundle("~/Scripts/js");
#endif
If you have debug="true" in web.config and are using Scripts/Styles.Render to reference the bundles in your pages, that should turn off both bundling and minification. BundleTable.EnableOptimizations = false will always turn off both bundling and minification as well (irrespective of the debug true/false flag).
Are you perhaps not using the Scripts/Styles.Render helpers? If you are directly rendering references to the bundle via BundleTable.Bundles.ResolveBundleUrl() you will always get the minified/bundled content.
To disable bundling and minification just put this your .aspx file
(this will disable optimization even if debug=true in web.config)
vb.net:
System.Web.Optimization.BundleTable.EnableOptimizations = false
c#.net
System.Web.Optimization.BundleTable.EnableOptimizations = false;
If you put EnableOptimizations = true this will bundle and minify even if debug=true in web.config
You can turn off minification in your bundles simply by Clearing your transforms.
var scriptBundle = new ScriptBundle("~/bundles/scriptBundle");
...
scriptBundle.Transforms.Clear();
I personally found this useful when wanting to bundle all my scripts in a single file but needed readability during debugging phases.
I tried a lot of these suggestions but noting seemed to work. I've wasted quite a few hours only to found out that this was my mistake:
#Scripts.Render("/bundles/foundation")
It always have me minified and bundled javascript, no matter what I tried. Instead, I should have used this:
#Scripts.Render("~/bundles/foundation")
The extra '~' did it. I've even removed it again in only one instance to see if that was really it. It was... hopefully I can save at least one person the hours I wasted on this.
Combine several answers, this works for me in ASP.NET MVC 4.
bundles.Add(new ScriptBundle("~/Scripts/Common/js")
.Include("~/Scripts/jquery-1.8.3.js")
.Include("~/Scripts/zizhujy.com.js")
.Include("~/Scripts/Globalize.js")
.Include("~/Scripts/common.js")
.Include("~/Scripts/requireLite/requireLite.js"));
bundles.Add(new StyleBundle("~/Content/appLayoutStyles")
.Include("~/Content/AppLayout.css"));
bundles.Add(new StyleBundle("~/Content/css/App/FunGrapherStyles")
.Include("~/Content/css/Apps/FunGrapher.css")
.Include("~/Content/css/tables.css"));
#if DEBUG
foreach (var bundle in BundleTable.Bundles)
{
bundle.Transforms.Clear();
}
#endif
There is also some simple way to control minification (and other features) manually. It's new CssMinify() transformer using, like this:
// this is in case when BundleTable.EnableOptimizations = false;
var myBundle = new StyleBundle("~/Content/themes/base/css")
.Include("~/Content/themes/base/jquery.ui.core.css" /* , ... and so on */);
myBundle.Transforms.Add(new CssMinify());
bundles.Add(myBundle);
// or you can remove that transformer in opposite situation
myBundle.Transforms.Clear();
That's convenient when you want to have some bundles special part only to be minified. Let's say, you are using some standard (jQuery) styles, which are getting under your feet (taking lots of excessive browser requests to them), but you want to keep unminified your own stylesheet. (The same - with javascript).
I combined a few answers given by others in this question to come up with another alternative solution.
Goal: To always bundle the files, to disable the JS and CSS minification in the event that <compilation debug="true" ... /> and to always apply a custom transformation to the CSS bundle.
My solution:
1) In web.config:
<compilation debug="true" ... />
2) In the Global.asax Application_Start() method:
protected void Application_Start() {
...
BundleTable.EnableOptimizations = true; // Force bundling to occur
// If the compilation node in web.config indicates debugging mode is enabled
// then clear all transforms. I.e. disable Js and CSS minification.
if (HttpContext.Current.IsDebuggingEnabled) {
BundleTable.Bundles.ToList().ForEach(b => b.Transforms.Clear());
}
// Add a custom CSS bundle transformer. In my case the transformer replaces a
// token in the CSS file with an AppConfig value representing the website URL
// in the current environment. E.g. www.mydevwebsite in Dev and
// www.myprodwebsite.com in Production.
BundleTable.Bundles.ToList()
.FindAll(x => x.GetType() == typeof(StyleBundle))
.ForEach(b => b.Transforms.Add(new MyStyleBundleTransformer()));
...
}
If you set the following property to false then it will disable both bundling and minification.
In Global.asax.cs file, add the line as mentioned below
protected void Application_Start()
{
System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
Here's how to disable minification on a per-bundle basis:
bundles.Add(new StyleBundleRaw("~/Content/foobarcss").Include("/some/path/foobar.css"));
bundles.Add(new ScriptBundleRaw("~/Bundles/foobarjs").Include("/some/path/foobar.js"));
Sidenote: The paths used for your bundles must not coincide with any actual path in your published builds otherwise nothing will work. Also make sure to avoid using .js, .css and/or '.' and '_' anywhere in the name of the bundle. Keep the name as simple and as straightforward as possible, like in the example above.
The helper classes are shown below. Notice that in order to make these classes future-proof we surgically remove the js/css minifying instances instead of using .clear() and we also insert a mime-type-setter transformation without which production builds are bound to run into trouble especially when it comes to properly handing over css-bundles (firefox and chrome reject css bundles with mime-type set to "text/html" which is the default):
internal sealed class StyleBundleRaw : StyleBundle
{
private static readonly BundleMimeType CssContentMimeType = new BundleMimeType("text/css");
public StyleBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
{
}
public StyleBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
{
Transforms.Add(CssContentMimeType); //0 vital
Transforms.Remove(Transforms.FirstOrDefault(x => x is CssMinify)); //0
}
//0 the guys at redmond in their infinite wisdom plugged the mimetype "text/css" right into cssminify upon unwiring the minifier we
// need to somehow reenable the cssbundle to specify its mimetype otherwise it will advertise itself as html and wont load
}
internal sealed class ScriptBundleRaw : ScriptBundle
{
private static readonly BundleMimeType JsContentMimeType = new BundleMimeType("text/javascript");
public ScriptBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
{
}
public ScriptBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
{
Transforms.Add(JsContentMimeType); //0 vital
Transforms.Remove(Transforms.FirstOrDefault(x => x is JsMinify)); //0
}
//0 the guys at redmond in their infinite wisdom plugged the mimetype "text/javascript" right into jsminify upon unwiring the minifier we need
// to somehow reenable the jsbundle to specify its mimetype otherwise it will advertise itself as html causing it to be become unloadable by the browsers in published production builds
}
internal sealed class BundleMimeType : IBundleTransform
{
private readonly string _mimeType;
public BundleMimeType(string mimeType) { _mimeType = mimeType; }
public void Process(BundleContext context, BundleResponse response)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (response == null)
throw new ArgumentNullException(nameof(response));
response.ContentType = _mimeType;
}
}
To make this whole thing work you need to install (via nuget):
WebGrease 1.6.0+
Microsoft.AspNet.Web.Optimization 1.1.3+
And your web.config should be enriched like so:
<runtime>
[...]
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
</dependentAssembly>
[...]
</runtime>
<!-- setting mimetypes like we do right below is absolutely vital for published builds because for some reason the -->
<!-- iis servers in production environments somehow dont know how to handle otf eot and other font related files -->
<system.webServer>
[...]
<staticContent>
<!-- in case iis already has these mime types -->
<remove fileExtension=".otf" />
<remove fileExtension=".eot" />
<remove fileExtension=".ttf" />
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".otf" mimeType="font/otf" />
<mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
<mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>
<!-- also vital otherwise published builds wont work https://stackoverflow.com/a/13597128/863651 -->
<modules runAllManagedModulesForAllRequests="true">
<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>
[...]
</system.webServer>
Note that you might have to take extra steps to make your css-bundles work in terms of fonts etc. But that's a different story.
Search for EnableOptimizations keyword in your project
So if you find
BundleTable.EnableOptimizations = true;
turn it false.
This does disable minification,
And it also disables bundling entirely
Just to supplement the answers already given, if you also want to NOT minify/obfuscate/concatenate SOME files while still allowing full bundling and minification for other files the best option is to go with a custom renderer which will read the contents of a particular bundle(s) and render the files in the page rather than render the bundle's virtual path. I personally required this because IE 9 was $*%#ing the bed when my CSS files were being bundled even with minification turned off.
Thanks very much to this article, which gave me the starting point for the code which I used to create a CSS Renderer which would render the files for the CSS but still allow the system to render my javascript files bundled/minified/obfuscated.
Created the static helper class:
using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
namespace Helpers
{
public static class OptionalCssBundler
{
const string CssTemplate = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";
public static MvcHtmlString ResolveBundleUrl(string bundleUrl, bool bundle)
{
return bundle ? BundledFiles(BundleTable.Bundles.ResolveBundleUrl(bundleUrl)) : UnbundledFiles(bundleUrl);
}
private static MvcHtmlString BundledFiles(string bundleVirtualPath)
{
return new MvcHtmlString(string.Format(CssTemplate, bundleVirtualPath));
}
private static MvcHtmlString UnbundledFiles(string bundleUrl)
{
var bundle = BundleTable.Bundles.GetBundleFor(bundleUrl);
StringBuilder sb = new StringBuilder();
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
foreach (BundleFile file in bundle.EnumerateFiles(new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, bundleUrl)))
{
sb.AppendFormat(CssTemplate + Environment.NewLine, urlHelper.Content(file.VirtualFile.VirtualPath));
}
return new MvcHtmlString(sb.ToString());
}
public static MvcHtmlString Render(string bundleUrl, bool bundle)
{
return ResolveBundleUrl(bundleUrl, bundle);
}
}
}
Then in the razor layout file:
#OptionalCssBundler.Render("~/Content/css", false)
instead of the standard:
#Styles.Render("~/Content/css")
I am sure creating an optional renderer for javascript files would need little to update to this helper as well.
If you're using LESS/SASS CSS transformation there's an option useNativeMinification which can be set to false to disable minification (in web.config). For my purposes I just change it here when I need to, but you could use web.config transformations to always enable it on release build or perhaps find a way modify it in code.
<less useNativeMinification="false" ieCompat="true" strictMath="false"
strictUnits="false" dumpLineNumbers="None">
Tip: The whole point of this is to view your CSS, which you can do in the browser inspect tools or by just opening the file. When bundling is enabled that filename changes on every compile so I put the following at the top of my page so I can view my compiled CSS eaily in a new browser window every time it changes.
#if (Debugger.IsAttached)
{
View CSS
}
this will be a dynamic URL something like https://example.com/Content/css/bundlename?v=UGd0FjvFJz3ETxlNN9NVqNOeYMRrOkQAkYtB04KisCQ1
Update: I created a web.config transformation to set it to true for me during deployment / release build
<bundleTransformer xmlns="http://tempuri.org/BundleTransformer.Configuration.xsd">
<less xdt:Transform="Replace" useNativeMinification="true" ieCompat="true" strictMath="false" strictUnits="false" dumpLineNumbers="None">
<jsEngine name="MsieJsEngine" />
</less>
</bundleTransformer>
This may become useful to someone in the future as the new framework, when setup through VS, gets a default web.config, web.Debug.config and web.Release.config. In the web.release.config you will find this line:
<compilation xdt:Transform="RemoveAttributes(debug)" />
this was seeming to override any inline changes I made. I commented this line out and we were gravy (in terms of seeing non-minified code in a "release" build)

How to disable open ASP.NET MVC site in IFrame?

As I have already mentioned in topic, I have a MVC site and I need to disable loading it into IFrame.
I have created simple page for testing purpose and I try to load into two IFrames my site and Google.com. I can see that my site is loaded but Google isn't. It means that it's necessary to change something in my MVC site.
<!DOCTYPE html>
<html>
<body>
<iframe src="http://localhost:61831/" width="1200" height="800">
<p>Your browser does not support iframes.</p>
</iframe>
<iframe src="http://google.com" width="1200" height="800">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
So what and where in MVC site I have to write to achieve that?
It is possible to use X-Frame-Options HTTP header attribute to avoid ASP.NET MVC application be opened in IFrame.
There are several different way to insert this attribute to HTTP header:
1.Configure IIS to add this attribute to all HTTP responses
2.Set this attribute in every necessary action method of every controller
public class HomeController : Controller
{
public ActionResult Index()
{
Response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
return View();
}
}
3.Create C# attribute in a way described here and apply it to action methods and controllers
[HttpHeader("X-Frame-Options", "SAMEORIGIN")]
public class HomeController : Controller
{
public ActionResult Index()
{
}
}
4.Set this attribute in Global.asax file
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
...
}
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
Response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
}
}
Simple and quick Solution is to add following in Global.asax -
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
Response.AddHeader("X-Frame-Options", "SAMEORIGIN");
}
Then give a try with iframe. Pages will not open in iframes. HTH.
You can also add an entry in web.config:
<system.webServer>
...
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="SAMEORIGIN" />
</customHeaders>
</httpProtocol>
...
</system.webServer>
You can configure IIS to always append the X-Frame-Options SAMEORIGIN header in it's responses.
From IIS Management Console, select your application.
In the main panel, double click Http Response Headers.
Click Add from the upper right pane.
Set the name to X-Frame-Options and the value to SAMEORIGIN then
click OK.
This should prevent your site from being loaded into an iframe on a different host, without using any javascript or any extra code.
See developper.mozilla.org for the header documentation and technet.microsoft.com for IIS' configuration.
As DrewMan suggested, you want to use X-Frame-Options header.
I would suggest you to download Nuget Package NWebsec and there's MVC specific package. Also check out the configuration part.

Why is my CSS bundling not working with a bin deployed MVC4 app?

I have bin deployed an MVC4 application to my hosting provider, based on advice given here and one or two on-the-fly fixes, but the most immediately apparent problem is that the bundling for css doesn't work. When I replace the bundle ref with explicit file refs, my css works again.
I am using a standard MVC4 RTM project template from VS2012. The provider is running IIS 7.5 and ASP.NET 4, and my previous MVC3 version of the same app worked fine. I am guessing I have grabbed a dependency somewhere of too low a version, and this might also contribute to my area based action link problem.
Technical symptoms are:
The line #Styles.Render("~/Content/css") renders as <link href="/Content/css?v=" rel="stylesheet"/>
UPDATE 11/4/2013:
The reason why this happens is because you have .js or .css at the end of your bundle name which causes ASP.NET to not run the request through MVC and the BundleModule.
The recommended way to fix this for better performance is to remove the .js or .css from your bundle name.
So /bundle/myscripts.js becomes /bundle/myscripts
Alternatively you can modify your web.config in the system.webServer section to run these requests through the BundleModule (which was my original answer)
<modules runAllManagedModulesForAllRequests="true">
<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>
Edit: I also noticed that if the name ends with 'css' (without the dot), that is a problem as well. I had to change my bundle name from 'DataTablesCSS' to 'DataTablesStyles' to fix my issue.
The CSS and Script bundling should work regardless if .NET is running 4.0 or 4.5. I am running .NET 4.0 and it works fine for me. However in order to get the minification and bundling behavior to work your web.config must be set to not be running in debug mode.
<compilation debug="false" targetFramework="4.0">
Take this bundle for jQuery UI example in the _Layout.cshtml file.
#Styles.Render("~/Content/themes/base/css")
If I run with debug="true" I get the following HTML.
<link href="/Content/themes/base/jquery.ui.core.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.resizable.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.selectable.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.accordion.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.autocomplete.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.button.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.dialog.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.slider.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.tabs.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.datepicker.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.progressbar.css" rel="stylesheet"/>
<link href="/Content/themes/base/jquery.ui.theme.css" rel="stylesheet"/>
But if I run with debug="false". I'll get this instead.
<link href="/Content/themes/base/css?v=myqT7npwmF2ABsuSaHqt8SCvK8UFWpRv7T4M8r3kiK01" rel="stylesheet"/>
This is a feature so you can easily debug problems with your Script and CSS files. I'm using the MVC4 RTM.
If you think it might be an MVC dependency problem, I'd recommend going into Nuget and removing all of your MVC related packages, and then search for the Microsoft.AspNet.Mvc package and install it. I'm using the most recent version and it's coming up as v.4.0.20710.0. That should grab all the dependencies you need.
Also if you used to be using MVC3 and are now trying to use MVC4 you'll want to go into your web.config(s) and update their references to point to the 4.0 version of MVC. If you're not sure, you can always create a fresh MVC4 app and copy the web.config from there. Don't forget the web.config in your Views/Areas folders if you do.
UPDATE: I've found that what you need to have is the Nuget package Microsoft.AspNet.Web.Optimization installed in your project. It's included by default in an MVC4 RTM app regardless if you specify the target framework as 4.5 or 4.0. This is the namespace that the bundling classes are included in, and doesn't appear to be dependent on the framework. I've deployed to a server that does not have 4.5 installed and it still works as expected for me. Just make sure the DLL gets deployed with the rest of your app.
Just to clarify a few things, System.Web.Optimization (aka Bundling/Minification) will work against 4.0. It is not depending on anything in 4.5, so there should be no problems there.
If script bundling is working, and its only an issue with CSS, perhaps the issue is with relative URLs?
I'd first look at the rendered page and see if you are getting references to the CSS bundle, i.e. something like:
<link href="/app/Content/css?v=oI5uNwN5NWmYrn8EXEybCI" rel="stylesheet"/>
If you are, then bundling is working, but something inside your CSS bundle is messed up. Usually this is due to relative URLs inside your CSS bundle being incorrect, i.e. if your images live under ~/Content, but you name your bundle ~/bundles/css, the browser will incorrectly look for images under ~/bundles.
Also, the default behavior is to disable bundling and minification when debug=true. So, if you do want optimizations enabled even when debug=true, you will need to force:
BundleTable.EnableOptimizations = true
Updated: With the new info that v="", that means the bundle was empty, you should verify that you are adding files to the bundle correctly, and that it found them. How are you including files to the bundle?
Omitting runAllManagedModulesForAllRequests="true" also worked for me. Add the following configuration in web.config:
<modules>
<remove name="BundleModule" />
<add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>
runAllManagedModulesForAllRequests will impose a performance hit on your website if not used appropriately. Check out this article.
Another thing to consider is the references cannot have the same name. For example, if you have jQuery UI in the libraries directory, and bundle its JavaScript file like so:
bundles.Add(new ScriptBundle("~/libraries").Include("~/libraries/jquery-ui/jqyery-ui.js"));
and then try to bundle its CSS files like so:
bundles.Add(new StyleBundle("~/libraries").Include("~/libraries/jquery-ui/jqyery-ui.css"));
...
it will fail. They have to have unique names. So do something like ScriptBundle("~/libraries/js")... and ScriptBundle("~/libraries/css")... or whatever.
As an addendum to the existing answers, none of which worked for me I found my solution HERE:
https://bundletransformer.codeplex.com/discussions/429707
The solution was to
right click the .less files in visual studio
Select properties
Mark the Build Action as Content
Redeploy
I did NOT need to remove extensionless handlers (as can be found in other solutions on the internet)
I did NOT have to add the <add name="BundleModule" type="System.Web.Optimization.BundleModule" /> web.config setting.
Hope this helps!
I encountered the same issue with CSS on a live environment. I followed all of the advise here and investigated how the bundling works behind the scene. This lead me to request that the .Net cache was cleared (I didn't have access to the app servers) which caused the bundling to start working on the app servers. However, when accessing the site via a load balancer with a CDN configured, although the bundle identifier was updated in the url, the bundle contained the old CSS. Simply flushing the CDN resolved the issue.
I hope this goes some way to helping some one else who may encounter this
One of my css files had an '_' character in the file name which caused issues.
Renamed your_style.css to yourstyle.css
I know this is an old issue, but people may still face this.
The following checks if the BundleModule exists in web.config and loaded,
and sets EnableOptimizations based on its existance.
This way wether it is available or not, the css/js references will work fine.
In other words:
If BundleModule is available, the bundeling/optimization will be enabled.
If BundleModule is not available, the bundeling/optimization will be disabled and automatically the full references will be used
instead.
Code:
public static void RegisterBundles(BundleCollection bundles)
{
// bundeling code here
// ...
// bundeling code here
bool bundelingModuleIsAvailable = false;
try {
bundelingModuleIsAvailable = HttpContext.Current.ApplicationInstance.Modules.AllKeys.Contains("BundleModule");
}
catch { }
if (!bundelingModuleIsAvailable)
System.Diagnostics.Debug.WriteLine("WARNING : optimization bundle is not added to Web.config!");
BundleTable.EnableOptimizations = bundelingModuleIsAvailable && !Debug_CheckIsRunning();
//Debug_CheckIsRunning is optional, incase you want to disable optimization when debugging yourself
BundleTable.EnableOptimizations = true;
}
private bool Debug_CheckIsRunning()
{//Check if debug is running
string moduleName = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName;
return (moduleName.Contains("iisexpress.exe") || moduleName.Contains(".vshost") || moduleName.Contains("vstest.executionengine") || moduleName.Contains("WebDev.WebServer"));
}
Just for history:
Check that all mentioned less/css files in bundle have Build Action = "Content".
There is no error if some files from bundle missing on destination server.
I had the same problem and it turned out to be a stupid mistake, the css files were not included in the project so they weren't published, make sure you view all files in the solution and add them to the project.
I was facing this problem while deploying the code in Azure websites. it did worked when I deployed build from visualstudio.com and wasn't when I tried to publish the build from visual studio 2013. the main problem was CSS Minification. I totally agree with 1st response to this question. but thought of sharing solution that worked for me, may be it will help you in fixing it.
basically when we deploy through VSO it generates minification files for css, js by kicking in system.web.Optimization, but when we do publish build from VS 2013 we have to take care of the below.
bundling-and-minification
1. make sure the folder structure and your bundler naming convention should be different. something like this.
bundles.Add(new StyleBundle("~/Content/materialize/mcss").Include(
"~/Content//materialize/css/materialize.css"));
2. add at the bottom of your bundleconfig definition
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Code removed for clarity.
BundleTable.EnableOptimizations = true;
}
3. make sure to add debug false in web.config (when you start local debuging VS2013 will give you a popup saying that you need to make sure to putting it back before deploying into prod. that itself explains much.
<system.web>
<compilation debug="true" />
<!-- Lines removed for clarity. -->
</system.web>
With Visual Studio 2015 I found the problem was caused by referencing the .min version of a javascript file in the BundleConfig when debug=true is set in the web.config.
For example, with jquery specifying the following in BundleConfig:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.min.js"));
resulted in the jquery not loading correctly at all when debug=true was set in the web.config.
Referencing the un-minified version:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js"));
corrects the problem.
Setting debug=false also corrects the problem, but of course that is not exactly helpful.
It is also worth noting that while some minified javascript files loaded correctly and others did not. I ended up removing all minified javascript files in favor of VS handling minification for me.
try this:
#System.Web.Optimization.Styles.Render("~/Content/css")
#System.Web.Optimization.Scripts.Render("~/bundles/modernizr")
It worked to me.
I'm still learning, and I've not figured it out yet why it is happening
To add useful information to the conversation, I came across 404 errors for my bundles in the deployment (it was fine in the local dev environment).
For the bundle names, I including version numbers like such:
bundles.Add(new ScriptBundle("~/bundles/jquerymobile.1.4.3").Include(
...
);
On a whim, I removed all the dots and all was working magically again:
bundles.Add(new ScriptBundle("~/bundles/jquerymobile143").Include(
...
);
Hope that helps someone save some time and frustration.
I had this issue while adding some packages from nuget and forgot to do an update
So first do an update of all packages installed in the project
Update-Package
In the Global.asax.cs add the following
BundleTable.EnableOptimizations = true;
css names must be consistent.
Names of jqueryUI css are not "jquery.ui.XXX" in Contents/themes/base folder .
so it should be :
wrong:
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
correct :
bundles.Add(new StyleBundle("~/Bundles/themes/base/css").Include(
"~/Content/themes/base/core.css",
"~/Content/themes/base/resizable.css",
"~/Content/themes/base/selectable.css",
"~/Content/themes/base/accordion.css",
"~/Content/themes/base/autocomplete.css",
"~/Content/themes/base/button.css",
"~/Content/themes/base/dialog.css",
"~/Content/themes/base/slider.css",
"~/Content/themes/base/tabs.css",
"~/Content/themes/base/datepicker.css",
"~/Content/themes/base/progressbar.css",
"~/Content/themes/base/theme.css"));
I tried in MVC5 and worked successfully.
You need to add this code in your shared View
#*#Scripts.Render("~/bundles/plugins")*#
<script src="/Content/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Kendo JS -->
<script src="/Content/kendo/js/kendo.all.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.web.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.aspnetmvc.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="/Content/bootstrap/js/bootstrap.min.js"></script>
<!-- Morris.js charts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="/Content/plugins/morris/morris.min.js"></script>
<!-- Sparkline -->
<script src="/Content/plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="/Content/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="/Content/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="/Content/plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script src="/Content/plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="/Content/plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="/Content/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="/Content/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="/Content/plugins/fastclick/fastclick.min.js"></script>
<!-- AdminLTE App -->
<script src="/Content/dist/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/Content/dist/js/demo.js"></script>
<!-- Common -->
<script src="/Scripts/common/common.js"></script>
<!-- Render Sections -->
#RenderSection("scripts", required: false)
#RenderSection("HeaderSection", required: false)
This solved my issue. I have added these lines in _layout.cshtml
#*#Scripts.Render("~/bundles/plugins")*#
<script src="/Content/plugins/jQuery/jQuery-2.1.4.min.js"></script>
<!-- jQuery UI 1.11.4 -->
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<!-- Kendo JS -->
<script src="/Content/kendo/js/kendo.all.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.web.min.js" type="text/javascript"></script>
<script src="/Content/kendo/js/kendo.aspnetmvc.min.js"></script>
<!-- Bootstrap 3.3.5 -->
<script src="/Content/bootstrap/js/bootstrap.min.js"></script>
<!-- Morris.js charts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="/Content/plugins/morris/morris.min.js"></script>
<!-- Sparkline -->
<script src="/Content/plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="/Content/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="/Content/plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="/Content/plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>
<script src="/Content/plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="/Content/plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="/Content/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<!-- Slimscroll -->
<script src="/Content/plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="/Content/plugins/fastclick/fastclick.min.js"></script>
<!-- AdminLTE App -->
<script src="/Content/dist/js/app.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/Content/dist/js/demo.js"></script>
<!-- Common -->
<script src="/Scripts/common/common.js"></script>
<!-- Render Sections -->
i had the same problem . i just convert
#Styles.Render("~/Content/css")
and #Scripts.Render("~/bundles/modernizr") to
#Styles.Render("/Content/css")
#Scripts.Render("/bundles/modernizr")
and its worked.
just dont forget to convert
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
to
#Scripts.Render("/bundles/jquery")
#Scripts.Render("/bundles/bootstrap")
have nice time

Resources