Web Development

Tips, tricks, experiences, and fun with ASP.NET, jQuery, and other web-related tech.

Tweaking Web API URL Request Validation

In working with a REST API project I’m on, I was tasked to create a DELETE operation that would take the resource ID in the URL path, like: DELETE /api/someresource/reallylongresourceidhere HTTP/1.1 The resource ID we had was really, really long base-64 encoded value. About 750 characters long. No, don’t bug me about why that was the case, just… stick with me. I had to get it to work in IIS and OWIN hosting. STOP. STOP RIGHT HERE. I’m going to tell you some ways to tweak URL request validation. This is a security thing. Security is Good....

Two Web API Gotchas

I just spent a day fighting these so I figured I’d share. You may or may not run into them. They do get pretty low-level, like, “not the common use case.” PROBLEM 1: Why Isn’t My Data Serializing as XML? I had set up my media formatters so the XML formatter would kick in and provide some clean looking XML when I provided a querystring parameter, like http://server/api/something?format=xml. I did it like this: var fmt = configuration.Formatters.XmlFormatter; fmt.MediaTypeMappings.Add(new QueryStringMapping("format", "xml", "text/xml")); fmt.UseXmlSerializer = true; fmt.WriterSettings.Indent = true; It seemed to work on super simple stuff, but then it seemed to arbitrarily...

AutoMapper, Autofac, Web API, and Per-Request Dependency Lifetime Scopes

I’m working on a new Web API project where I want to use AutoMapper for some type conversion. As part of that, I have a custom AutoMapper type converter that takes in some constructor parameters so the converter can read configuration values. I’m using Autofac for dependency injection (naturally). Historically, I’ve been able to hook AutoMapper into dependency injection using the ConstructServicesUsing method and some sort of global dependency resolver, like: Mapper.Initialize(cfg => { cfg.ConstructServicesUsing(t => DependencyResolver.Current.GetService(t)); cfg.CreateMap(); }); That works great in MVC or in other applications where there's a global static like that. In those cases, the...

MVC, Task.Run, and HttpContext.Current

For reasons I won’t get into, we recently ended up with a scenario in MVC where we needed to use RenderAction to get some data into a view. Some of the data was exposed via async calls to services. The challenge is that RenderAction doesn’t support asynchronous controller actions. To accomplish the task, we ended up with a synchronous controller action that used Task.Run to get data from certain async calls. And, yeah, I know that’s not really the greatest thing in the world but there wasn’t a great way around that. That landed us with a new...

Using ASP.NET MVC 5 IAuthenticationFilter for Authentication Challenges

One of the new ASP.NET MVC 5 features, authentication filters, has dreadfully little documentation. There’s a Visual Studio Magazine article on it, but that basically replicates the AuthorizeAttribute in a different way. It doesn’t really explain much else. Diving into the source doesn’t tell you too much, either. The context you get in the filter has a little more of an idea about what you should be doing, but… it’s really not enough. The real magic happens in the ControllerActionInvoker.InvokeAction method. The source shows that the general flow is like this: MVC action gets...

FluentValidation and MVC - From Server to Client

We do a lot of interesting stuff with FluentValidation at work and more than a few times I've had to give the whiteboard presentation of how a server-side FluentValidation validator makes it to jQuery validation rules on the client and back. I figured it was probably time to just write it up so I can refer folks as needed. Let's start out with a simple model we want to validate. We'll carry these examples with us in the walkthrough so you have something concrete to tie back to. public class MyModel { public string Name { get; set;...

Adding Custom Files to an MSDeploy Package

As part of some of my web projects I have "plugin assemblies" that aren't directly referenced by the project but are things I want included in my deployment package. I tried following the instructions on this fairly popular blog entry, but it didn't seem to work - that blog entry tells you to modify a set of files during a stage in the packaging pipeline "CopyAllFilesToSingleFolderForPackageDependsOn" and that target never actually fired for me. In fact, I threw an <Error> call in there just to see if I could get the build to fail and… no luck. It also...

How to Set Up JSHint in Sublime Text 2 Using SublimeLinter

I’ve got Sublime Text 2 and I love it. (I even have a package I wrote myself for it.) I wanted to get JSHint going in it and I saw that there was a nice JSHint package… but then I found SublimeLinter, which seems to be the King of Sublime Text Linting Packages. It basically can run any lint for any program type and gives a nice inline highlighting for errors. Very cool, very flexible. And very hard to figure out all the steps needed to get JSHint up and running properly on a clean system. So here’s...

Unfortunate Things with JSON, jQuery UI Datepicker, and Dates

I’m trying to write an HtmlHelper extension that lets you dump out options that build a jQuery UI datepicker on the client. (I know there are some of these out there, but for various reasons I won’t get into… I get to make one, too.) Something that will let me do this: @Html.DatePickerFor(m => m.SomeDate); In doing that, I’ve uncovered a lot of frustration around getting the options specified on the server over to the client and working in a consistent format. JSON date serialization continues to be a joke....

Putting Controllers in Plugin Assemblies for ASP.NET MVC

With Autofac (particularly the multitenant extensions) I see a lot of questions come through that boil down to this: I have an ASP.NET MVC project. I have some controllers in a plugin assembly that isn't referenced by the main project. At application startup, I do some scanning and use Autofac to dynamically register the controllers. For some reason I get an error when I try to visit one of these controllers. How can I have a controller in a plugin assembly? Shannon Deminick has a nice blog article that explains this in a different context - similar question,...

jQuery.each and Object Boxing

I just spent like six hours trying to figure this out, so profit from my experience. I have some custom code wiring up jQuery Validation in a form and for some reason, the jQuery "html" method was causing a "HIERARCHY_REQUEST_ERR: DOM Exception 3" whenever validation errors were being displayed. After banging my head against it for a while and getting some help from a co-worker, we found it came down to the $.each iterator. I was compiling up a list of error messages and using the $.each to add them to settings for a jQuery validator. It looked...

Windows "Command Prompt Here" Generator

I love context menu "command prompt here" shortcuts. Every time a new VS version comes out, or a different prompt is available that I need, I create a new one. In the past, I've tried to maintain a whole roundup of current versions, but that's been tough. Different operating systems come out, I need to tweak this or that to make things work, and I end up having to edit and re-package the whole bundle. It's also a pain for people wanting the installers – you want some, but not all; the tool isn't quite what you want but...

Html.DemoPartial - Side-by-Side Render and Code for Partial Views

I was working on an ASP.NET MVC site for demonstrating some internal concepts recently. One of the things I wanted to show was how to use some HtmlHelper extension methods. I wanted the viewer to be able to see the rendered output and then flip to see the code, sort of like how you see in snazzy demos like the DevExpress MVC Extensions. Here's a little screencast/demo of what I'm talking about. Unable to display content. Adobe Flash is required. So... how do you do that? Here's how it...

ASP.NET MVC, aria-required, and jQuery Unobtrusive Validation

I saw this interesting article about using model metadata in ASP.NET MVC to add the aria-required attribute to required input fields. The approaches there are all totally valid and work great if you have the requirement to add the attribute on the server-side. However, if you're using jQuery unobtrusive validation, you've already got some metadata you can use from the client side. Required fields all get the data-val-required attribute associated with them: <input data-val="true" data-val-required="This is a required field." id="RequiredField" name="RequiredField" type="text" value="" /> The attribute only exists on required fields. With that,...

Data Type Validation and Model Binding in ASP.NET MVC

When validating input in a web forms application, you need to validate data types on the client and server side because you're working with text boxes and server controls. When you move to MVC, the client-side validation is still an interesting problem to solve, but the server-side validation all happens as a by-product of model binding. The DefaultModelBinder has some special built-in provisions to handle data type parsing errors and automatically convert those into standardized model state errors. If you're writing a custom model binder and you want to participate in this... Get the...