I would like to minify and obfuscate javascript files of my Web Application (not MVC). I based my code on this simple configuration: https://bundletransformer.codeplex.com/discussions/541419, but
it seems to have no effect on js files when viewed from the browser. I did not understand if Bundle Transformer is only applicable to MVC Web Applications. I installed BundleTransformer.Core, BundleTransformer.Yui, Microsoft.AspNet.Web.Optimization.
Global.asax.cs:
public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{
var nullOrderer = new NullOrderer();
var scriptBundle = new CustomScriptBundle("~/jscbundle/");
scriptBundle.Include("~/js/main.js");
scriptBundle.IncludeDirectory("~/js/", "*.js", true);
scriptBundle.Orderer = nullOrderer;
bundles.Add(scriptBundle);
BundleTable.EnableOptimizations = true;
}
}
protected void Application_Start(object sender, EventArgs e)
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Web.Config:
<system.web>
<compilation debug="false" targetFramework="4.5" />
...
</system.web>
<bundleTransformer xmlns="http://tempuri.org/BundleTransformer.Configuration.xsd">
<core>
<css>
<minifiers>
<add name="NullMinifier" type="BundleTransformer.Core.Minifiers.NullMinifier, BundleTransformer.Core" />
<add name="YuiCssMinifier" type="BundleTransformer.Yui.Minifiers.YuiCssMinifier, BundleTransformer.Yui" />
</minifiers>
<translators>
<add name="NullTranslator" type="BundleTransformer.Core.Translators.NullTranslator, BundleTransformer.Core" enabled="false" />
</translators>
</css>
<js defaultMinifier="YuiJsMinifier">
<minifiers>
<add name="NullMinifier" type="BundleTransformer.Core.Minifiers.NullMinifier, BundleTransformer.Core" />
<add name="YuiJsMinifier" type="BundleTransformer.Yui.Minifiers.YuiJsMinifier, BundleTransformer.Yui" />
</minifiers>
<translators>
<add name="NullTranslator" type="BundleTransformer.Core.Translators.NullTranslator, BundleTransformer.Core" enabled="false" />
</translators>
</js>
</core>
</bundleTransformer>
Bundle and Minify comes by default in normal Asp.net project in VS2015 onwards.
Minify is not restricted to MVC, we can use it for any files.
In Android , we can obfuscate the complete project.
Please let me know which version of VS are you using ? so i can provide assistance accordingly.
I recommend you to read the Rick Anderson's posts about using of Microsoft ASP.NET Web Optimization Framework with Web Forms and Web Pages.
Related
In previous versions all of these settings could be added and tweaked in the Web.Config file using something like the code below:
<staticContent>
<mimeMap fileExtension=".webp" mimeType="image/webp" />
<!-- Caching -->
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="96:00:00" />
</staticContent>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="*/*" enabled="false" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
However, with the Web.Config no longer being around in ASP.NET vNext, how do you adjust settings like this? I have searched the net and the ASP.NET Github repo, but not come across anything - any ideas?
As "agua from mars" states in the comments, if you're using IIS you can use IIS's static file handling, in which case you can use the <system.webServer> section in a web.config file and that will work as it always did.
If you're using ASP.NET 5's StaticFileMiddleware then it has its own MIME mappings that come as part of the FileExtensionContentTypeProvider implementation. The StaticFileMiddleware has a StaticFileOptions that you can use to configure it when you initialize it in Startup.cs. In that options class you can set the content type provider. You can instantiate the default content type provider and then just tweak the mappings dictionary, or you can write an entire mapping from scratch (not recommended).
ASP.NET Core - mime mappings:
If the extended set of file types you are providing for the entire site are not going to change, you can configure a single instance of the ContentTypeProvider class, and then leverage DI to use it when serving static files, like so:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddInstance<IContentTypeProvider>(
new FileExtensionConentTypeProvider(
new Dictionary<string, string>(
// Start with the base mappings
new FileExtensionContentTypeProvider().Mappings,
// Extend the base dictionary with your custom mappings
StringComparer.OrdinalIgnoreCase) {
{ ".nmf", "application/octet-stream" }
{ ".pexe", "application/x-pnal" },
{ ".mem", "application/octet-stream" },
{ ".res", "application/octet-stream" }
}
)
);
...
}
public void Configure(
IApplicationBuilder app,
IContentTypeProvider contentTypeProvider)
{
...
app.UseStaticFiles(new StaticFileOptions() {
ContentTypeProvider = contentTypeProvider
...
});
...
}
I've created a new MVC5 asp.net website with SignalR (v2.1.1.0)
The SignalR part is hosted inside the web application.
I've added a new Hub : MainHub.cs
using BackEnd.Models;
using BackEnd.Utils;
using Microsoft.AspNet.SignalR;
using Microsoft.Practices.Unity;
namespace BackEnd.Hubs
{
public class MainHub : Hub
{
// Code
}
}
Then I've added a new StartUp file by doing a right click on the project -> add new 'OWIN Statup class' and named it 'Startup.cs' :
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(BackEnd.Startup))]
namespace BackEnd
{
public class Startup
{
public static Configs.ContainerInjection container;
public void Configuration(IAppBuilder app)
{
container = new Configs.ContainerInjection();
container.Configure();
app.MapSignalR();
}
}
}
And this is my config file : Web.config
<appSettings>
<add key="owin:AutomaticAppStartup" value="true" />
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
...
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
</system.web>
But when I launch the application on Local IIS, the 'Configuration' method is not called inside the Startup file. But it does work when launched on IIS Express (localhost:3405)
I use 'DefaultApp Pool' with Framework v4.0 and Integrated Pipeline mode and 'Microsoft.Owin.Host.SystemWeb' is correctly placed in the '/bin' folder.
Is there anything I've done wrong ?
Install SystemWeb host and you will be fine.
Install-Package Microsoft.Owin.Host.SystemWeb
This installs a httphandler to call the starup.
The OwinStartupAttribute is in the Microsoft.Owin.dll. Do you have this in your bin folder? What other Owin dlls do you have in the application bin folder?
I have created a base Page class and trying to save object in session variable but it is giving me Object reference not set to an instance of an object. error. my object is initialized and have values.
I have added enableSessionState="true" and sessionState mode="InProc" settings in Web.config file.
ASP.NET State Service is also running
using System;
using System.Web;
using System.Globalization;
using System.Threading;
using System.Xml.Linq;
public class BasePage : System.Web.UI.Page
{
public BasePage()
{
string catalog = "" + HttpContext.Current.Request.QueryString["c"];
if (catalog != "")
{
Engine eng = new Engine();
TEngine engine = eng.GetEngines(catalog.ToUpper());
if (engine != null)
{
HttpContext.Current.Session["CurrentEngine"] = engine;
}
}
}
}
web.config:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<sessionState mode="InProc" timeout="60" cookieless="false" />
<pages enableSessionState="true">
<controls>
<add src="~/Components/menu.ascx" tagName="Menu" tagPrefix="uc" />
<add src="~/Components/footer.ascx" tagName="Footer" tagPrefix="uc" />
<add src="~/Component/tree.ascx" tagName="Tree" tagPrefix="uc" />
</controls>
</pages>
<httpModules>
<add type="System.Web.SessionState.SessionStateModule" name="Session"/>
</httpModules>
</system.web>
</configuration>
According to this MSDN document, the Page's properties (Context, Request, etc) will be assigned after the construction of the Page object. You can move the code which make use of these properties to either Init or Load event handlers.
And there is no need to use HttpContext.Current inside a web page. Simply use this.Context.
Adding this as an answer, since it seems to have solved your problem:
The construction of your page objects occurs too early in the ASP.NET life cycle, and HttpContext.Current is not available yet. Move this code to one of the initialization methods or some such, instead of the constructor.
I have seen ASP.NET MVC Without Visual Studio, which asks,
Is it possible to produce a website based on ASP.NET MVC, without using Visual Studio?
And the accepted answer is, yes.
Ok, next question: how?
Here's an analogy. If I want to create an ASP.NET Webforms page, I load up my favorite text editor, create a file named Something.aspx. Then I insert into that file, some boilerplate:
<%# Page Language="C#"
Debug="true"
Trace="false"
Src="Sourcefile.cs"
Inherits="My.Namespace.ContentsPage"
%>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Title goes here </title>
<link rel="stylesheet" type="text/css" href="css/style.css"></link>
<style type="text/css">
#elementid {
font-size: 9pt;
color: Navy;
... more css ...
}
</style>
<script type="text/javascript" language='javascript'>
// insert javascript here.
</script>
</head>
<body>
<asp:Literal Id='Holder' runat='server'/>
<br/>
<div id='msgs'></div>
</body>
</html>
Then I also create the Sourcefile.cs file:
namespace My.Namespace
{
using System;
using System.Web;
using System.Xml;
// etc...
public class ContentsPage : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Literal Holder;
void Page_Load(Object sender, EventArgs e)
{
// page load logic here
}
}
}
And that is a working ASPNET page, created in a text editor. Drop it into an IIS virtual directory, and it's working.
What do I have to do, to make a basic, hello, World ASPNET MVC app, in a text editor? (without Visual Studio)
Suppose I want a basic MVC app with a controller, one view, and a simple model. What files would I need to create, and what would go into them?
ok, I examined Walther's tutorial and got a basic MVC site running.
The files required were:
Global.asax
App_Code\Global.asax.cs
App_Code\Controller.cs
Views\HelloWorld\Sample.aspx
web.config
That's it.
Inside the Global.asax, I provide this boilerplate:
<%# Application Inherits="MvcApplication1.MvcApplication" Language="C#" %>
And that MvcApplication class is defined in a module called Global.asax.cs which must be placed into the App_Code directory. The contents are like this:
using System.Web.Mvc;
using System.Web.Routing;
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{arg}", // URL with parameters
new { // Parameter defaults
controller = "HelloWorld",
action = "Index",
arg = "" } );
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
The Controller.cs provides the logic to handle the various requests. In this simple example, the controller class is like this:
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class HelloWorldController : Controller
{
public string Index()
{
return "Hmmmmm...."; // coerced to ActionResult
}
public ActionResult English()
{
return Content("<h2>Hi!</h2>");
}
public ActionResult Italiano()
{
return Content("<h2>Ciao!</h2>");
}
public ViewResult Sample()
{
return View(); // requires \Views\HelloWorld\Sample.aspx
}
}
}
The Controller class must be named XxxxxController, where the Xxxxx portion defines the segment in the URL path. For a controller called HelloWorldController, the URL path segment is HelloWorld. Each public method in the Controller class is an action; the method is called when that method name is included in another segment in the url path . So for the above controller, these URLs would result in invoking the various methods:
http:/ /server/root/HelloWorld (the default "action")
http:/ /server/root/HelloWorld/Index (same as above)
http:/ /server/root/HelloWorld/English
http:/ /server/root/HelloWorld/Italiano
http:/ /server/root/HelloWorld/Sample (a view, implemented as Sample.aspx)
Each method returns an Action result, one of the following: View (aspx page), Redirect, Empty, File (various options), Json, Content (arbitrary text), and Javascript.
The View pages, such as Sample.aspx in this case, must derive from System.Web.Mvc.ViewPage.
<%# Page Language="C#"
Debug="true"
Trace="false"
Inherits="System.Web.Mvc.ViewPage"
%>
That's it! Dropping the above content into an IIS vdir gives me a working ASPNET MVC site.
(Well, I also need the web.config file, which has 8k of configuration in it. All this source code and configuration is available to browse or download.)
And then I can add other static content: js, css, images and whatever else I like.
You would do exactly what you did above, because you wouldn't use a model or controller in a hello world app.
All visual studio does is provide you with file creation wizards, so in theory, all you need to do is create the right files. If you want detailed specifications for the MVC project structure, good luck, most documentation is written on the assumption you are using visual studio, but you might be able to go through a tutorial step by step, and puzzle it out.
Your best bet is to find a downloadable demo project, use visual studio to reverse engineer the project structure, or try one of the open source .net IDE.
Well, this is how the default VS skeleton for an MVC 1.x app looks like:
Content
Site.css
Controllers
AccountController.cs
HomeController.cs
Models
Scripts
(all the jquery scripts)
MicrosoftAjax.js
MicrosoftMvcAjax.js
Views
web.config
Account
ChangePassword.aspx
ChangePasswordSuccess.aspx
LogOn.aspx
Register.aspx
Home
About.aspx
Index.aspx
Shared
Error.aspx
LogOnUserControl.ascx
Site.master
Default.aspx
Global.asax
web.config
Dunno if that's what you're looking for... the key here is obviously the web.config file.
Note: if you added namespace you must have an assembly.
web.config example for Cheeso example project on opensuse linux under mono project.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core" />
</configSections>
<appSettings>
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<!-- <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> -->
</assemblies>
</compilation>
<authentication mode="None"></authentication>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<!-- <add namespace="System.Web.Helpers" />
<add namespace="System.Web.WebPages" /> -->
</namespaces>
</pages>
<httpHandlers>
<add path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler, dotless.Core" />
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<add name="dotless" path="*.less" verb="*" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Abstractions" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<dotless minifyCss="false" cache="true" web="false" />
</configuration>
I'm having difficulty making IIS 7 correctly compress a Json result from ASP.NET MVC. I've enabled static and dynamic compression in IIS. I can verify with Fiddler that normal text/html and similar records are compressed. Viewing the request, the accept-encoding gzip header is present. The response has the mimetype "application/json", but is not compressed.
I've identified that the issue appears to relate to the MimeType. When I include mimeType="*/*", I can see that the response is correctly gzipped. How can I get IIS to compress WITHOUT using a wildcard mimeType? I assume that this issue has something to do with the way that ASP.NET MVC generates content type headers.
The CPU usage is well below the dynamic throttling threshold. When I examine the trace logs from IIS, I can see that it fails to compress due to not finding a matching mime type.
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files" noCompressionForProxies="false">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/json" enabled="true" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="application/xaml+xml" enabled="true" />
<add mimeType="application/json" enabled="true" />
</staticTypes>
</httpCompression>
Make sure your %WinDir%\System32\inetsrv\config\applicationHost.config contains these:
<system.webServer>
<urlCompression doDynamicCompression="true" />
<httpCompression>
<dynamicTypes>
<add mimeType="application/json" enabled="true" />
<add mimeType="application/json; charset=utf-8" enabled="true" />
</dynamicTypes>
</httpCompression>
</system.webServer>
From the link of #AtanasKorchev.
As #simon_weaver said in the comments, you might be editing the wrong file with a 32 bit editor on a 64 bit Windows, use notepad.exe to make sure this file is indeed modified.
I have successfully used the approach highlighted here.
Use this guide
None of these answers worked for me. I did take note of the application/json; charset=utf-8 mime-type though.
I recommend this approach
Create CompressAttribute class, and set target action.
The ActionFilterAttribute approach updated for ASP.NET 4.x and Includes Brotli.NET package.
using System;
using System.IO.Compression;
using Brotli;
using System.Web;
using System.Web.Mvc;
public class CompressFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("BR"))
{
response.AppendHeader("Content-encoding", "br");
response.Filter = new BrotliStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}