Action based request encoding in ASP.NET MVC

Posted by Siim on June 12th, 2012

Sometimes it’s needed to set different request/response encoding for some of the requests. For example when some third party sends requests (or responses) in some predefined encoding and doesn’t support UTF8, whereas ASP.NET uses UTF8 for all requests and responses by default.

ASP.NET allows us to change that encoding through web.config’s <globalization /> element, like:

<globalization requestEncoding="ISO-8859-1" responseEncoding="ISO-8859-1" />

But this way it affects all the request and that’s not what I want. Luckily, ASP.NET allows web.config file inheritance, by creating separate web.config file in a subfolder or using <location path=””> element in main web.config file.

In case of webforms it’s simple – we need to create location-based configuration for one of our .aspx files. But how to achieve it with MVC you might ask?

Actually, it’s exactly the same. For path part you need to provide full route url to you action. Path attribute doesn’t need to be a physical file or folder, but path in the sense of url. Only drawback is that when changing routes you must remember to change it in the web.config also. And here is the final result, which affects only one action:

<configuration>
...
<location path="path/to/your/actionmethod">
	<system.web>
		<globalization requestEncoding="ISO-8859-1" responseEncoding="ISO-8859-1" />
	</system.web>
</location>
...
</configuration>

Minifying CSS & JS in ASP.NET MVC application

Posted by Siim on June 10th, 2011

In my project I have many small JavaScript files containing mostly jQuery plugins. Also there are many CSS files, because I prefer to split my CSS declarations to multiple files based on some context. All this results in many static files that must be loaded in every page load which increases latency.

So I decided to combine multiple files into one single file and also minify it. I looked for some libraries that would get the job done for me and I stick with YUI Compressor which requires Java runtime. I still want to step through readable javascript when I’m developing the app so I decided to combine and minify files only when I’m compiling in release mode, but we will get to that point later on. There were two action I needed to take to achieve this. I needed to modify the web project to include after build action for combining files and to write some kind of extension that’s either loads debuggable source files or compressed files. None of the steps were hard.

Post build step is actually two actions – temporarily combining multiple files into a single file and then minifying that file with YUI Compressor. It gets triggered only when building in a release mode. All the required tools including YUI Compressor are included in VCS so that all dependencies are there when developer checks out code.

<PropertyGroup>
	<yuiCompressor>java -jar ..\..\Tools\yuicompressor\yuicompressor-2.4.2.jar</yuiCompressor>
 </PropertyGroup>
 <Target Name="AfterBuild">
	...
	<CallTarget Targets="Minimize" Condition="'$(Configuration)' == 'Release'" />
 </Target>
 <Target Name="Minimize">
	<GetAssemblyIdentity AssemblyFiles="bin\$(ProjectName).dll">
	  <Output TaskParameter="Assemblies" ItemName="assemblyInfo" />
	</GetAssemblyIdentity>
	<ItemGroup>
	  <JqJsFiles Include="Content\Scripts\jquery.*.js;Content\Scripts\json2.js;" />
	</ItemGroup>
	<ItemGroup>
      <OldVersions Include="Content\Scripts\jq.plugins.min-*.js" />
    </ItemGroup>
	<!-- js Merge and Minimize -->
	<ReadLinesFromFile File="%(JqJsFiles.Identity)">
	  <Output TaskParameter="Lines" ItemName="jqJsLines" />
	</ReadLinesFromFile>
	<WriteLinesToFile File="Content\Scripts\jq.merged.js" Lines="@(jqJsLines)" Overwrite="true" />
	<Delete Files="@(OldVersions)" />
	<Exec Command="$(yuiCompressor) --type js &quot;$(ProjectDir)Content\Scripts\jq.merged.js&quot; -o Content\Scripts\jq.plugins.min-%(assemblyInfo.Version).js --charset utf-8" />
	<Delete Files="Content\Scripts\jq.merged.js" />
</Target>
<PropertyGroup>
	<CopyAllFilesToSingleFolderForPackageDependsOn>
		CollectMinifiedFilesInPackage;
		$(CopyAllFilesToSingleFolderForPackageDependsOn);
	</CopyAllFilesToSingleFolderForPackageDependsOn>
</PropertyGroup>
<Target Name="CollectMinifiedFilesInPackage" Condition="'$(Configuration)' == 'Release'">
	<ItemGroup>
	  <_JsFiles Include="Content\Scripts\jq.plugins.min-*.js" />
	  <FilesForPackagingFromProject Include="%(_JsFiles.Identity)">
		<DestinationRelativePath>Content\Scripts\%(Filename)%(Extension)</DestinationRelativePath>
	  </FilesForPackagingFromProject>
	</ItemGroup>
</Target>

As you can see, I include assembly version number (which is generated by build) in the names of the compressed files. This way I can always refer to correct JS files which are accordance with the given assembly. There’s also a target called CopyAllFilesToSingleFolderForPackageDependsOn which is required to include those compressed files in the MSDeploy package because they are not included in the web project and therefore not automatically included.

For the other part I wrote a partial view to load CSS & scripts files based on the configuration. And I use the partial view in my layout files (or wherever I need) to include all required resources. A part of the view:

@if (HttpContext.Current.IsDebuggingEnabled)
{
	@Html.Script("~/Content/Scripts/jquery-1.4.4.js")
	@Html.Script("~/Content/Scripts/jquery-ui-1.8.9.custom.min.js")
	@Html.Script("~/Content/Scripts/jquery.ui.datepicker-en-GB.js?" + DateTime.Now.Ticks)
	@Html.Script("~/Content/Scripts/jquery.selectboxes.js?" + DateTime.Now.Ticks)
	@Html.Script("~/Content/Scripts/jquery.tooltip.js?" + DateTime.Now.Ticks)
	@Html.Script("~/Content/Scripts/json2.js?" + DateTime.Now.Ticks)
}
else
{
	@Html.Script("~/Content/Scripts/jquery-1.4.4.min.js")
	@Html.Script("~/Content/Scripts/jquery-ui-1.8.9.custom.min.js")
	@Html.Script(string.Format("~/Content/Scripts/jq.plugins.min-{0}.js", Html.AssemblyVersion()))
}

Side note: I append the timestamp at the end of the file names to prevent any caching issues in development environment

I make the decision which files to load based on the debug configuration in the web.config, not based on the build configuration in the compile time. I also deploy all the resource files (compressed and original) so I am able to switch between them easily, without recompiling and deploying.

That’s it. No custom out-of-the-solution build scripts needed. And the solution can be also applied to ASP.NET Webforms applications with little modification in including files.

Simplifying ASP.NET MVC controllers with custom action results

Posted by Siim on February 2nd, 2011

When I am developing MVC applications I see that there are some common behavior for certain types of actions (eg. list view, edit view) which means similar code. A common solution to that problem is to create a base controller with that behavior. And that’s also how I tried to solve the problem first. I created base controllers for each view type and their related actions. But it created new problems.

I ended up with a multi-level inheritance tree which made it difficult to track down things. It wasn’t possible to look at the controller and simply say what it is doing. Some of the actions were defined at the upper level that required implementations at the lower level and so on, which created a lot of jumping between classes.
And then there was a common inheritance problem – I needed some behavior from base controller but not all, so I had to implement methods I really didn’t need. Or I needed behavior from multiple base controllers.
Third, it created a big constructors in controllers with all different dependencies required by base controller classes.

I thought about using approach called controllerless actions, but after a little research I found it is too complicated with a given structure. Luckily I can create custom action results that can encapsulate all the logic and data for returning a result for given action. But then I found this post which described separating WHAT of an action result from the HOW. By that I mean that my custom action result contains all the required information to execute an action, but the execution logic is in different object – in an action result invoker I created.

By using this approach I was able to separate all that execution logic from base controllers to separate action invoker. And controller was only responsible for returning a proper action method result with all relevant information based on the input. No repetitive execution logic anymore. For that, I created a base ActionMethodResult which is so called marker base class for my custom action method results.

public abstract class ActionMethodResult : ActionResult
{
	public override void ExecuteResult(ControllerContext context)
	{
		throw new InvalidOperationException("Action should be executed through action invoker");
	}
}

A one simple action method result implementation looks like this. It contains a task to execute and a result to return when task execution was successful and other one for failure cases.

public class TaskActionResult<TEntity> : ActionMethodResult
	where TEntity : IEntity<int>
{
	private readonly Func<ITask<TEntity>> _task;
	private readonly Func<TaskResult<TEntity>, ActionResult> _successContinuation;
	private readonly Func<TaskResult<TEntity>, ActionResult> _failureContinuation;

	public TaskActionResult(Func<ITask<TEntity>> task, Func<TaskResult<TEntity>, ActionResult> successContinuation, Func<TaskResult<TEntity>, ActionResult> failureContinuation)
	{
		_task = task;
		_successContinuation = successContinuation;
		_failureContinuation = failureContinuation;
	}

	public Func<ITask<TEntity>> Task
	{
		get { return _task; }
	}

	public Func<TaskResult<TEntity>, ActionResult> SuccessContinuation
	{
		get { return _successContinuation; }
	}

	public Func<TaskResult<TEntity>, ActionResult> FailureContinuation
	{
		get { return _failureContinuation; }
	}
}

But it’s not the case with all action results. Some of them just take some inputs and invoker decides how to respond to that. The main point is the same – invoker generates some response based on the given action method result in the context of current request. Action invoker for TaskActionResult is like this.

public class TaskActionResultInvoker<TEntity> : ITaskActionMethodResultInvoker<TEntity>
	where TEntity : IEntity<int>
{
	public ActionResult Invoke(TaskActionResult<TEntity> actionResult, ControllerContext controllerContext)
	{
		if (!controllerContext.Controller.ViewData.ModelState.IsValid)
		{
			return actionResult.FailureContinuation(null);
		}

		var result = actionResult.Task().Run();
		if (!result.ValidationResults.IsValid)
		{
			result.ValidationResults.AddToModelState(controllerContext.Controller.ViewData.ModelState);
			return actionResult.FailureContinuation(result);
		}

		return actionResult.SuccessContinuation(result);
	}
}

Then I created a custom IActionInvoker where I overrode the CreateActionResult method to create a proper ActionResult based on my custom action method result. Each of my action invoker held it’s own dependencies so I needed to create a façade for that which got my action invoker as a constructor argument so it could be resolved by my container. The creation of the facades and action invokers is a bit tedious, but it was a compromise I was willing ta make.

public class InjectingActionInvoker : ControllerActionInvoker, IActionMethodResultCreator
{
	private readonly IServiceLocator _serviceLocator;

	public InjectingActionInvoker(IServiceLocator serviceLocator)
	{
		_serviceLocator = serviceLocator;
	}

	protected override ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
	{
		if (IsActionMethodResult(actionReturnValue))
		{
			var result = CreateActionMethodResult(actionReturnValue, controllerContext);

			return IsActionMethodResult(result)
				? CreateActionResult(controllerContext, actionDescriptor, result)
				: result;
		}
		return base.CreateActionResult(controllerContext, actionDescriptor, actionReturnValue);
	}

	public ActionResult CreateActionMethodResult(object actionReturnValue, ControllerContext controllerContext)
	{
		var wrappedResultType = CreateActionInvokerFacadeType(actionReturnValue);

		var invokerFacade = (IActionMethodResultInvoker)_serviceLocator.Resolve(wrappedResultType);

		return invokerFacade.Invoke(actionReturnValue, controllerContext);
	}

	private static Type CreateActionInvokerFacadeType(object actionReturnValue)
	{
		var actionMethodResultType = actionReturnValue.GetType();

		Type openWrappedType;
		Type wrappedResultType;

		if (actionMethodResultType.IsGenericImplementation(typeof(TaskActionResult<>)))
		{
			openWrappedType = typeof(TaskActionResultInvokerInvokerFacade<>);
			wrappedResultType = openWrappedType.MakeGenericType(actionMethodResultType.GetGenericArguments()[0]);
		}
		// code for other types of action results removed for brevity
		else
		{
			openWrappedType = typeof(ActionMethodResultInvokerFacade<>);
			wrappedResultType = openWrappedType.MakeGenericType(actionMethodResultType);
		}

		return wrappedResultType;
	}
}

Note the recursive call to the CreateActionResult method. It is because my action method results my return other action method results for some execution paths, which in turn need to be invoked with their own type of invokers. So invokers are executed so long as result is “regular” ActionResult which can be executed using ASP.NET MVC built-in behavior. 

Finally, when all hooked up, my controller action looks like this. Simple, clean and without inheritance.

[HttpPost]
public ActionResult Edit(int id, ViewModel item)
{
	item.Id = id;

	return new TaskActionResult<Entity>(
		() => _taskFactory.ForSave(() => CreateEntityFromViewModel(item)),
		success => SaveSuccessResult(success, "Task executed!"),
		SaveFailureResult);
}

Now I’m able to create much more simple controllers in the maintenance point of view, they are better to follow. It also improved testability. Because in my opinion, inheritance is pain in the butt regarding testing. This approach allowed me to easily test the result of the controller action (which is basically a plain data) separately from the execution of that result. Which I can do in an isolation compared to the approach when I was using controller inheritance which also resulted in some sort of tests inheritance.

ASP.NET MVC RenderAction with action method overloads

Posted by Siim on September 5th, 2010

In ASP.NET MVC, every controller method which is public and not marked with NonAction attribute is considered as an action. And action name is the same as method name. But you can also provide ActionName attribute with specified action name. There is also different attributes to constrain actions to handle only specified HTTP methods (GET, POST, PUT etc). All that information is used when finding which controller method to execute.

So, when technically (in a sense of C#) you can create many method overloads for a controller method, you end up with runtime exception when you don’t further restrain those actions. For example, consider following controller:

public class ProductController : Controller
{
	public ActionResult Edit(int id)
	{
		return View("Edit");
	}

	public ActionResult Edit(int id, ProductItem item)
	{
		return View("EditPost");
	}
}

public class ProductItem
{
	public int Id { get; set; }

	public string Name { get; set; }
}

When executing Edit action, MVC don’t know which method overload to execute, because current route could be handled by both of the Edit methods. But when decorating first method with HttpGet attribute and the second with HttpPost attribute, it works well.

Now, the trouble comes when you execute one of such methods from the view with RenderAtion method. Lets say you have two controllers:

public class ProductController : Controller
{
	public ActionResult Edit(int id)
	{
		return View("Edit");
	}

	[HttpPost]
	public ActionResult Edit(int id, ProductItem item)
	{
		return View("EditPost");
	}
}

public class ProductDetailController : Controller
{
	public ActionResult Edit(int id)
	{
		return View("EditDetail");
	}

	[HttpPost]
	public ActionResult Edit(int id, ProductDetailItem item)
	{
		return View("EditDetailPost");
	}
}

public class ProductDetailItem
{
	public string Type { get; set; }
}

public class ProductItem
{
	public int Id { get; set; }

	public string Name { get; set; }
}

ProductController is used to display product form view. On that form, I also call RenderAction to render Edit method on the ProductDetailController which displays some product sub-detail form. When executing first ProductController.Edit method, all works fine. When I submit product form, then the second Edit method is executed (because it handles POST requests).

At first, it looked like some weird behavior. But after when I gave a thought how MVC resolves which action method to execute, it all works out. It’s because RenderAction uses the same algorithm to resolve actions as a regular action link. So pay attention when using same pattern with controllers and actions.

MvcContrib grid with extended sorting capabilities

Posted by Siim on July 7th, 2010

Lately I’ve been doing development on ASP.NET MVC and using MvcContrib grid to render simple grids. I have to say, it is very easy to use and extendible in every way. If I feel that something is missing or I want to change some behavior, then I just need to implement the proper interfaces and inject my own implementation for what I need.

For views I use view models with data annotations which specify how some data should be displayed on the view. I wanted to use data annotations also for specifying which properties should be rendered as sortable columns and which is the default one. Grid doesn’t do any sorting by itself, it solely relies on the input (which is a good thing, IMHO).

Fortunately, it was very easy to add. I needed only two things – customize the MVC model metadata provider to include my custom values and create a custom ColumnBuilder for the grid that could read values I included in the metadata. Brad Wilson has a nice post about how to extend model metadata providers. The code for the OrderByAttribute and with the bit that extends model metadata, is here:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class OrderByAttribute : Attribute
{
	public OrderByAttribute()
		: this(SortDirection.Ascending, false)
	{
	}

	public OrderByAttribute(SortDirection sortOrder, bool isDefault)
	{
		SortOrder = sortOrder;
		IsDefault = isDefault;
	}

	public SortDirection SortOrder { get; set; }

	public bool IsDefault { get; set; }
}

public class GridMetaDataProvider : DataAnnotationsModelMetadataProvider
{
	public const string SortableValueName = "Sortable";

	protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType,
		Func<object> modelAccessor, Type modelType, string propertyName)
	{
		var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

		var orderByAttribute = attributes.OfType<OrderByAttribute>().FirstOrDefault();
		if (orderByAttribute!=null)
		{
			metadata.AdditionalValues.Add(SortableValueName, orderByAttribute);
		}

		return metadata;
	}
}

Next I need to create a column builder, similarly to AutoColumnBuilder which comes with MvcContrib. Unfortunately, I cannot extend that class because there are no extension point, but I used it as a guidance. For each property from metadata, I execute the following code, to apply sorting metadata:

var isSortable = property.AdditionalValues.ContainsKey(GridMetaDataProvider.SortableValueName);
column.Sortable(isSortable);
column.SortColumnName(property.PropertyName);

That’s all about building columns from metadata. Next thing I need to do, is to tell the grid which column is used for initial sorting. Because grid wants object of type GridSortOptions as an input, it is created by the controller. So I wrote a little extension method to populate GridSortOptions from model metadata.

public static GridSortOptions ApplyDefault<TItem>(this GridSortOptions sortOptions) where TItem : ListItemBase
{
	// When sort options is specified, don't apply default values
	if (sortOptions != null && !string.IsNullOrEmpty(sortOptions.Column)) return sortOptions;

	var property = typeof (TItem).GetProperties().Where(ContainsDefaultOrderBy).FirstOrDefault();
	if (property == null) return sortOptions;

	var newSortOptions = sortOptions ?? new GridSortOptions();
	newSortOptions.Column = property.Name;
	return newSortOptions;
}

private static bool ContainsDefaultOrderBy(PropertyInfo property)
{
	var orderBy = (OrderByAttribute)property.GetCustomAttributes(typeof (OrderByAttribute), false).FirstOrDefault();
	return orderBy != null && orderBy.IsDefault;
}

That’s it. Now you can decorate your view model with attributes and grid takes care of the rest.


Copyright © 2007 Siim Viikman's blog.