Use Of Model Binder In MVC And Web API

The goal is to show how to create a custom binder to use in both MVC and WEB API applications.

The classic use of model binder is to capture information of a form but here, my Model Binder has the responsibility to hold information about the environment like logged user, URL and other things.

What we need?

  1. MVC Application.
  2. Web API Application.
  3. Model Binder itself.

I have created one Application with MVC and Web API together.

Let's get started.

The model binder class with both MVC and Web API implementations.

Binders\EnvironmentInfoModelBinder.cs

  1. namespace FSL.ModelBinderInMvcAndWebApi.Binders {  
  2.     public class EnvironmentInfoModelBinder: System.Web.Mvc.IModelBinder, System.Web.Http.ModelBinding.IModelBinder {  
  3.         /// <summary>   
  4.         /// MVC version   
  5.         /// </summary>   
  6.         /// <param name="controllerContext"></param>   
  7.         /// <param name="bindingContext"></param>   
  8.         /// <returns></returns>   
  9.         public object BindModel(System.Web.Mvc.ControllerContext controllerContext,  
  10.                 System.Web.Mvc.ModelBindingContext bindingContext) {  
  11.                 var info = new Models.EnvironmentInfo();  
  12.                 info.RequestedUrl = controllerContext.RequestContext.HttpContext.Request.Url.ToString();  
  13.                 info.UserId = GetLoggedUser();  
  14.                 // you also can get form/request properties   
  15.                 return info;  
  16.             }  
  17.             /// <summary>   
  18.             /// WEB API version   
  19.             /// </summary>   
  20.             /// <param name="actionContext"></param>   
  21.             /// <param name="bindingContext"></param>   
  22.             /// <returns></returns>   
  23.         public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext,  
  24.             System.Web.Http.ModelBinding.ModelBindingContext bindingContext) {  
  25.             var info = new Models.EnvironmentInfo();  
  26.             info.RequestedUrl = actionContext.Request.RequestUri.ToString();  
  27.             info.UserId = GetLoggedUser();  
  28.             // you also can get form/request properties   
  29.             bindingContext.Model = info;  
  30.             return true;  
  31.         }  
  32.         private string GetLoggedUser() {  
  33.             //just a sample   
  34.             return "3242423423";  
  35.         }  
  36.     }  
  37. }  
We use a model binder as a parameter of the MVC and Web API Action Result.

The parameter environmentInfo will contain all the information we want about the URL and logged user and other things.

The use of Model Binder for Web API is given.

Services/Controllers/PersonApiController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Http;  
  6. using FSL.ModelBinderInMvcAndWebApi.Models;  
  7. namespace FSL.ModelBinderInMvcAndWebApi.Services.Controllers {  
  8.     [RoutePrefix("api/person")]  
  9.     public class PersonApiController: ApiController {  
  10.         [Route("")]  
  11.         public IHttpActionResult Get(Models.EnvironmentInfo environmentInfo) {  
  12.             var result = new {  
  13.                 EnvironmentInfo = environmentInfo  
  14.             };  
  15.             return Ok(result);  
  16.         }  
  17.     }  
  18. }  
The use of Model Binder in MVC is given.

Controllers/HomeController.cs
  1. using FSL.ModelBinderInMvcAndWebApi.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. namespace FSL.ModelBinderInMvcAndWebApi.Controllers {  
  8.     public class HomeController: Controller {  
  9.         public ActionResult Index(Models.EnvironmentInfo environmentInfo) {  
  10.             return View();  
  11.         }  
  12.     }  
  13. }  
  14. The Model Binder configuration  
  15. for MVC:  
Global.asax.cs
  1. public class MvcApplication: System.Web.HttpApplication {  
  2.     protected void Application_Start() {  
  3.         ModelBinders.Binders.Add(typeof(Models.EnvironmentInfo), new Binders.EnvironmentInfoModelBinder());  
  4.     }  
  5. }  
The Model Binder configuration for Web API

App_Start/WebApiConfig.cs
  1. public static class WebApiConfig {  
  2.     public static void Register(HttpConfiguration config) {  
  3.         config.BindParameter(typeof(Models.EnvironmentInfo), new Binders.EnvironmentInfoModelBinder());  
  4.     }  
  5. }  
Let me know, if you have others scenarios for model binders.

Download full source code.

I hope, it helps.

Up Next
    Ebook Download
    View all
    Learn
    View all