Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. Show all posts

Sunday, October 6, 2013

ASP.NET MVC: Current route values implicitly used by Url.Action

I really don't like when I work with statically-typed language like C# and still need to rely on strings or other loosely-typed constructs for things that may be strongly-typed. ASP.NET MVC went its way towards strongly-typing and now offers things like strongly-typed view models, but still lacks official built-in support for building internal links and URLs without using plain controller and action strings.

Fortunately, here is where MVC Futures comes in (available on NuGet for MVC 3 or 4). It offers a nice expression-based extension methods to build links (on HtmlHelper):

Html.ActionLink<TheController>(c => c.TheAction(theParam))

and URLs (on UrlHelper):

Url.Action<TheController>(c => c.TheAction(theParam))

It's working fine and it protects me from working with those ugly string-based methods and it is also a very convenient way to specify the target action parameters - in definitely nicer way then manually building the RouteValuesCollection required by those traditional methods.

But there is one not well-known feature of MVC (at least I haven't heard a lot about it) that for me seems to be disturbing here - MVC is reusing the route values from the current request when building URLs and no other value specified. This maybe makes some sense for the string-based methods (you don't need to build those RouteValuesCollections over and over again), but it makes no sense for the expression-based approach as the compiler enforces specifying all the parameters explicitly in order to build a lambda expression that compiles.

And here comes the nasty bug I've recently spent some hours on - passing null value is like not passing a value at all. MVC puts null under the appropriate key in the RouteValuesCollection, it then goes down to Route.GetVirtualPath method, which also takes the current route values from the RequestContext. And then the evil happens - the low-level System.Web.Routing's method ParsedRoute.Bind ignores the null value and - bang - it takes the value from the current request, if any accidentally matches by the parameter name.

It means that when trying to build an URL that passes parameter param equal to null and the current request accidentally have parameter named also param (regardless of its type or existence of any logical connection), the request's param value will be passed instead our explicitly demanded null value. And I can see no way to pass null in this case.

Actually, the bug (or feature?) exists in case of string-based URL builder methods, too. But here it is much more visible and obviously wrong.

The only way to fix that strange implicit parameter inheritance by name I know is to work around it - either by removing the name collision by renaming one of the parameters (yuck!) or by using own extension method.

I've created my own extension method to generate URLs/links that has the same signature as the buggy ones and placed it in the namespace more visible than those replaced (you'd better check your usings carefully). Here is the UrlHelper extension I have - HtmlHelper implementation generally calls UrlHelper and wraps its result in a link, so I'll omit it here. The method calls the same methods as the original method being replaced, but it tweaks the RequestContext instance: instead of passing the instance available in UrlHelper (which contains those conflicting route values from the current request), I'm creating new RequestContext reusing Route and IRouteHandler instances from the current request, leaving the actual route values empty. This way there's no possibility for the current values to "infect" our URL building process anymore. Interesting is that RouteData constructor doesn't enforce the values being set, anyway.

public static string Action<TController>(this UrlHelper helper, Expression<Action<TController>> action)
    where TController : Controller
{
    // we need to recreate RequestContext without values, to override the MVC "feature"
    // that replaces null specified in action with value inherited from current request
    var currentRouteData = helper.RequestContext.RouteData;
    var fixedRouteData = new RouteData(currentRouteData.Route, currentRouteData.RouteHandler);
    var fixedRequestContext = new RequestContext(helper.RequestContext.HttpContext, fixedRouteData);

    var valuesFromExpr = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(action);
    var vpd = helper.RouteCollection.GetVirtualPathForArea(fixedRequestContext, valuesFromExpr);
    return vpd == null ? null : vpd.VirtualPath;
}

Well, it seems to be yet another example of the fact that null is rather vague and problematic thing. It can represent many different notions, depending on the context and implementation - like no value, empty value, inherited value etc. Althouth ASP.NET MVC treats null as "inherit the value" not only in this case, I'd always prefer being explicit about that kind of behaviors.

Tuesday, September 25, 2012

Keeping server and client side in sync - enforcing contract compatibility

In our project which is an ASP.NET MVC application, quite a lot of features are implemented at the client side, with JavaScript, which is talking with the server using JSONs. Besides the web client, we have a mobile client application, which is driven by the separate API, provided by the same MVC application, a bit WebAPI style, again using JSONs. No rocket science.

As all of these three parts are growing and changing quickly (sometimes way too quickly), we were struggling with incompatibility between what the JavaScript or mobile client expects to receive and what the server is returning, due to the changes not being applied on both sides. Refactorings, functional changes or even correcting a typo affected these server-client interactions. Changing a property name is so easy with ReSharper that we're often not taking enough attention to spot possible impact at the borders between the layers. What's worse, we're relying heavily on the default model binding behavior of ASP.NET MVC - this means that even parameter names in action methods became part of our public API that we need to take care of. And by taking care I mean either not ever changing once-published name, or update all the possible clients together with the server-side backend deployment (that includes forcing all mobile app users to upgrade - nightmare!).

We decided we need a cheap, reliable and universal method that prevents unintended changes in our public contracts - action names, parameter types and names, returned types structures, names of properties etc.

Good and well maintained suite of integration tests will probably do the job, but unfortunately we still don't have one (and we're not the last ones, are we?). And I suppose the suite would be quite huge to cover good range of unintentional changes we can possibly introduce. Second thought was to implement some quirky tests that would use reflection to go through the codebase and fail if the implementation differs from what we expect. But it would be better to invest that considerable amount of time needed to write these kind of specifications in writing real integration tests.

Finally we took a simpler approach. We decided to be more explicit in what is our external API and what is not. We've created a binary contract definition using few steps. Let's see it on this simple example:

public class StadiumController
{
     public ActionResult GetByCapacity(int? minCapacity, int? maxCapacity)
     {
          var min = minCapacity ?? 0;
          var max = maxCapacity ?? int.MaxValue;
          return Json(Stadiums.Where(x => x.Capacity >= min && x.Capacity <= max));
     }
}

1. enclose the input parameters of action methods in "input model" classes

public class StadiumByCapacityInputModel
{
     public int? MinCapacity { get; set; }
     public int? MaxCapacity { get; set; }
}

public class StadiumController
{
     public ActionResult GetByCapacity(StadiumByCapacityInputModel input)
     {
          var min = input.MinCapacity ?? 0;
          var max = input.MaxCapacity ?? int.MaxValue;
          return Json(Stadiums.Where(x => x.Capacity >= min && x.Capacity <= max));
     }
}

2. change the return types of action methods to "output model" classes

public class StadiumByCapacityInputModel
{
     public int? MinCapacity { get; set; }
     public int? MaxCapacity { get; set; }
}

public class StadiumOutputModel
{
     public string Name { get; set; }
     public int Capacity { get; set; }
}

public class StadiumController
{
     public IEnumerable<StadiumOutputModel> GetByCapacity(StadiumByCapacityInputModel input)
     {
          var min = input.MinCapacity ?? 0;
          var max = input.MaxCapacity ?? int.MaxValue;
          var stadiums = Stadiums.Where(x => x.Capacity >= min && x.Capacity <= max);

          return stadiums.Select(x => new StadiumOutputModel() 
          {
               Name = x.Name,
               Capacity = x.Capacity
          };
     }
}

3. extract interfaces from the controllers

public class StadiumByCapacityInputModel
{
     public int? MinCapacity { get; set; }
     public int? MaxCapacity { get; set; }
}

public class StadiumOutputModel
{
     public string Name { get; set; }
     public int Capacity { get; set; }
}

public interface IStadium
{
     IEnumerable<StadiumOutputModel> GetByCapacity(StadiumByCapacityInputModel input);
}

public class StadiumController : IStadium
{
     public IEnumerable<StadiumOutputModel> GetByCapacity(StadiumByCapacityInputModel input)
     {
          var min = input.MinCapacity ?? 0;
          var max = input.MaxCapacity ?? int.MaxValue;
          var stadiums = Stadiums.Where(x => x.Capacity >= min && x.Capacity <= max);

          return stadiums.Select(x => new StadiumOutputModel() 
          {
               Name = x.Name,
               Capacity = x.Capacity
          };
     }
}

4. move these interfaces and input/output models far from the controller so that ReSharper-driven refactorings do not affect it - to the separate "contract" libraries.

5. include the libraries as referenced DLLs in our project

6. tweak ASP.NET MVC's default ActionInvoker to handle non-ActionResult return types (not needed with ASP.NET Web API - the actions in Web API controllers by design return POCO objects)

Now we treat the contract libraries like separate projects. We actually keep them in Libs folder and check it in to our main project as binaries, but just having it in a separate solution will do the job. The solution for contract library is configured so that the built output files go directly into the Libs folder, what is not possible without manual check-out of the previous binaries. This guarantees that no one checks in any changes in contract code without the new contract binaries and it also raises the level of explicitness. We've effectively made the development around contracts more difficult to ensure that all the changes done in contracts definitions are made deliberately and with proper consideration.

Whenever someone breaks the contract requirements (without modifying the binary contract properly), the project just doesn't compile - either the interface is not implemented or there is some kind of type mismatch. Moreover, having the contract definition in a separate physical project makes managing, documenting or versioning easier.

There is one thing that may seem to be a serious downside. We need to map our input model classes from contract to some "real" domain objects from the main codebase in order to use it. And the same with return types - we often need to map domain objects back to match types defined in the contract. It is a lot more fuss, but again - it makes the contract very explicit and visible. Easy cases of mapping can be handled with the tools like AutoMapper. More complicated cases may exist when the codebase starts to differ from the contract and we need to keep backward compatibility (like when the clients are mobile apps). In that cases again - it's even better to have all the transformations explicit and in one place and the mapping code becomes more helpful than annoying.

Saturday, September 22, 2012

Non-ActionResult action return type in ASP.NET MVC

In ASP.NET MVC, there's quite silly behavior when the controller's action method returns type that is not ActionResult-derived. The default ActionInvoker, which is responsible for invoking action code and interpret its result, checks if the returned instance is ActionResult and if not, returns plain string representation of the object (type name by default):

protected virtual ActionResult CreateActionResult(
    ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
{
    if (actionReturnValue == null)
    {
        return new EmptyResult();
    }

    ActionResult actionResult = (actionReturnValue as ActionResult) ??
        new ContentResult { Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture) };
    return actionResult;
}

I can see no real-life scenario in which ToString result returned as plain content can be useful. This in practice means that in ASP.NET MVC we're forced to use ActionResult or its derived types. This is especially annoying when you want your action method to be defined in an interface or used somewhere as a delegate.

The issue was solved much better in ASP.NET Web API - the actions in Web API controllers by design return POCO objects that are serialized correctly before sending it to the wire depending on the request and configuration - as XML, JSON etc.

To achieve similiar result in "normal" MVC controllers, let's replace the default ControllerActionInvoker right after creating the controller - in ControllerFactory - with our derived implementation that just overrides the virtual CreateActionResult method:

public class MyControllerFactory : DefaultControllerFactory
{
    public override IController CreateController(RequestContext context, string controllerName)
    {
        var controller = base.CreateController(context, controllerName);
        return ReplaceActionInvoker(controller);
    }

    private IController ReplaceActionInvoker(IController controller)
    {
        var mvcController = controller as Controller;
        if (mvcController != null)
            mvcController.ActionInvoker = new ControllerActionInvokerWithDefaultJsonResult();
        return controller;
    }
}

public class ControllerActionInvokerWithDefaultJsonResult : ControllerActionInvoker
{
    public const string JsonContentType = "application/json";

    protected override ActionResult CreateActionResult(
        ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue)
    {
        if (actionReturnValue == null)
            return new EmptyResult();

        return (actionReturnValue as ActionResult) ?? new ContentResult()
        {
            ContentType = JsonContentType,
            Content = JsonConvert.SerializeObject(actionReturnValue)
        };
    }
}

This simple implementation just serializes the returned objects to JSON, but it's easy to implement something more sophisticated here, like content negotiation patterns like Web API has. Feel free to use it and extend it if you find it useful - I've published it as a Gist for your convenience.

Thursday, April 5, 2012

Strongly typed links within ASP.NET MVC areas

Recently we've started to utilize concept of areas in our ASP.NET MVC application to separate different products provided by our application. We are going to have some controllers with the same names in different areas, so when linking, we'll need to specify the area name (if different than the current request's one). But we're used to strongly-typed url generation using extensions from MVC Futures like Html.ActionLink<T> with lambdas (Html.ActionLink<HomeController>(x => x.About(), "Home") etc. Unfortunately, these two requirements don't work well together.

MVC Futures extensions (known also as Microsoft.Web.Mvc) are good at getting the controller and action name from provided controller type and action lambda, but they don't get the area correctly. It's probably because there's no 100% correct way to determine in which area the controller lies. In most cases, we could guess that from the namespace - when creating area within Visual Studio, it creates the directory for controllers under Areas.AreaName.Controllers. But that's just a convention and there's no guarantee that it's always followed.

MVC Futures offers a solution - we can mark our controllers within areas with an attribute:

[ActionLinkArea("First")]
public class BillingController : Controller
{
}

This is understood by MVC Futures' strongly-typed helpers and when building a link to BillingController they'll use "First" area correctly.

Unfortunately, our requirements were more complicated. We have another area we use to expose some of our controllers through the RESTful API. And linking rules are as follows:

  • when current request is within First or Second area, we're linking as described above - target area is determined by target controller
  • but, when current request is within API area, we should link to API alternative controller (if available).

My first idea was to inherit from ActionLinkAreaAttribute and override the target area name for API calls, but unfortunately the attribute class is sealed. It means that we can't make use of that standard behavior and need to create our own.

After some fiddling with source code I've written my own versions of helper methods I need. My implementations conform to my own attribute, which allows to set up the default area name and fall back to standard MVC behavior (staying in current area) for API calls. Here's how to use it:

[LinkWithinArea("First", OrSwitchTo = "Api")]
public class BillingController : Controller
{
}

Now, whenever the helper method is building a link typed with BillingController, it'll generate link to Api area for calls from Api area or to First area for all other calls. OrSwitchTo parameter is optional - when omitted, LinkWithinArea will behave just like the built-in ActionLinkArea. No need to specify area all the time when building a links.

I've published the attribute and helpers code as a Gist, feel free to use it.

Saturday, March 31, 2012

ASP.NET MVC and overlapping routes

ASP.NET routing in MVC allows us to define how different URLs are mapped to the controllers, actions, action parameters etc. It is quite simple and in some cases it seems even too simple. In our MVC application we had a requirement that we should accept these two path patterns:

{controller}/{action}
{controller}.aspx/{action}

The first one is the default, we want our generated links to go this route. The second one is legacy, but it's required to work correctly. We could've set up some kind of redirects from old route to the default one, but we've thought it'll be easier to define a separate route in our application that will map to the same controllers as the default route.

Easier said than done. The first attempt looked like that:

routes.MapRoute("Default", "{controller}/{action}", 
new { controller = "Home", action = "Index" });
routes.MapRoute("Legacy", "{controller}.aspx/{action}",
new { controller = "Home", action = "Index" });

Seems trivial, but doesn't work. When requested Home.aspx, the application failed to find the controller named "Home.aspx". Well, the default route eagerly matched the controller variable and missed the fact that the second route seems to be better. Now I remember, the docs clearly state that finding the route stops on first match and we should arrange our routes from most specific to most generic ones.

OK, let's then change the order of our routes, so that we'll catch legacy ones first:

routes.MapRoute("Legacy", "{controller}.aspx/{action}", 
new { controller = "Home", action = "Index" });
routes.MapRoute("Default", "{controller}/{action}",
new { controller = "Home", action = "Index" });

Looks like working, both "Home.aspx" and "Home" are mapped to HomeController. But now all our links generated by MVC helpers (like Html.ActionLink) have .aspx extension. We don't want to expose this route as it is for backwards compatibility only. I've found the explanation and the insight I needed in Craig Stuntz's article. Generally, when building an URL, the helpers' behavior is similiar to parsing scenario. The first route that can be satisfied with route values given is chosen. We're passing controller and action values to Html.ActionLink, so the first route matches.

But Craig's article got me on the right track:

routes.MapRoute("Legacy", "{controller}.{extension}/{action}", 
new { controller = "Home", action = "Index" }, new { extension = "aspx" });
routes.MapRoute("Default", "{controller}/{action}",
new { controller = "Home", action = "Index" });

I've modified the first, legacy route, introduced the extension variable in place of "aspx" and defined a constraint in the fourth parameter, stating that extension variable have to be equal to aspx. This way only URLs like Home.aspx match the first route and ActionLink helpers don't use it (unless a route value named extension and equal to "aspx" is passed).

Tuesday, March 20, 2012

HTTP protocol breaking in ASP.NET MVC

HTTP clients (such as browsers) are designed to handle different error codes differently and there are a lot of reasons why server-side errors have different status codes than those triggered by users. Depending on status code, responses are cached differently, web crawlers are indexing differently and so on.

Recently, durring error handling review in our project, I've learned how ASP.NET MVC obeys HTTP protocol rules in terms of status codes. And unfortunately, there are some pretty easy cases where it doesn't. See this simple controller:

public class TestController : Controller
{
public ActionResult Index(int test, string html)
{
return Content("OK");
}
}

MVC handles missing controllers/actions properly, as 404 Not Found:

Let's now try to call the Index action without parameters:

MVC couldn't bind parameter values to an action and throws an exception, which yields 500 Internal Server Error status code. According to the HTTP protocol, it means that something unexpected happened on the server, but it is server's own problem, not that the request was wrong ("hey, I have some problems at the moment, can't help you, come back later"). But that's not true, I wouldn't say that missing parameter is an unexpected situation, and definitely it's the request what is wrong. The protocol has better solutions for that kind of situations - like 400 Bad Request ("hey, I've tried to help you but you're doing something wrong and I can't understand you").

Another example:

MVC has some validation rules that protects the server from potentially malicious requests, like cross-site scripting. But again, those cases are handled with 500 Internal Server Error, despite that it's obviously the client's fault - again 400 Bad Request will work here better. Purely from the HTTP protocol point of view, 500 Internal Server Error here is like admitting that the malicious request actually broke something on the server.

How can we fix these two? For example by modifying the response generated by MVC on error. We can add this code to our Global.asax.cs:

protected void Application_Error()
{
var lastError = Server.GetLastError();
if (lastError is ArgumentException || lastError is HttpRequestValidationException)
{
Server.ClearError();
Response.StatusCode = (int) HttpStatusCode.BadRequest;
}
}

It checks for type of exception thrown and changes the status code to more appropriate 400 Bad Request in these two cases mentioned.

Tuesday, November 22, 2011

ReSharper and external ASP.NET MVC views

The project I currently work in is based on ASP.NET MVC and, beside main Web project, it can be extended using additional plugin-style libraries, that we import from specified directories and register in main application. Those plugin libraries can contain additional view files (.aspx or .ascx) - to support that, we're storing it as embedded resources and we have custom VirtualPathProvider that resolves it in main Web application.

The problem we were struggling with for quite a long time was that ReSharper was unable to resolve those views correctly, getting lost on Control definition in the first line of view. This caused whole file to be not understood, a lot of errors and fix suggestions were showing up and with several views like this, the performance was dramatically low.

Recently I've spent some time to investigate it more carefully and it turned out that the reason is fairly simple. This has nothing to do with embedded resource setting or not standard file locations. The only thing to do was to place standard Web.config file for views in each external project that contains ASP.NET MVC views.

Here are the lines that ensures ReSharper knows what to do with .aspx/.ascx files (for ASP.NET MVC 2):

<configuration>
<system.web>
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
</configuration>