Use of Model Binder in MVC and Web API

Also available in portuguese

In this article I show you how to create a Model Binder class to use both MVC and Web API .

What do we need?

– A web project for those platforms MVC + Web API. You can create it from Visual Studio.
– A class that will implement interfaces for both platforms above.
– Config the Model Binder class in those platforms.

What is the goal?

– Return me information about the logged-on user’s environment, URL that was requested, credentials, browser information, and other things;

Model Binder class:

public class EnvironmentInfoModelBinder : System.Web.Mvc.IModelBinder, System.Web.Http.ModelBinding.IModelBinder
    {
        ///
<summary>
        /// MVC version
        /// </summary>

        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext,
            System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var info = new Models.EnvironmentInfo();
            info.RequestedUrl = controllerContext.RequestContext.HttpContext.Request.Url.ToString();
            info.UserId = GetLoggedUser();

            // you also can get form/request properties

            return info;
        }

        ///
<summary>
        /// WEB API version
        /// </summary>

        /// <param name="actionContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext,
            System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
        {
            var info = new Models.EnvironmentInfo();
            info.RequestedUrl = actionContext.Request.RequestUri.ToString();
            info.UserId = GetLoggedUser();

            // you also can get form/request properties

            bindingContext.Model = info;

            return true;
        }

        private string GetLoggedUser()
        {
            //just a sample
            return "3242423423";
        }
    }

MVC configuration (Global.asax):

protected void Application_Start()
        {
            ModelBinders.Binders.Add(typeof(Models.EnvironmentInfo), new Binders.EnvironmentInfoModelBinder());
        }

Web API configuration (WebApiConfig.cs):


public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            config.BindParameter(typeof(Models.EnvironmentInfo), new Binders.EnvironmentInfoModelBinder());
        }
    }

Usability in MVC Controller:

public ActionResult Index(Models.EnvironmentInfo environmentInfo)
        {
            return View();
        }

Usability in Web API Controller:

public IHttpActionResult Get(Models.EnvironmentInfo environmentInfo)
        {
            var result = new
            {
                EnvironmentInfo = environmentInfo
            };

            return Ok(result);
        }

This is it. I hope it helped.

Use of Model Binder in MVC and Web API

Model Binder no MVC e Web API: Questions, suggestions and feedbacks will be appreciated. Good luck!

Do complete download of the source code on github.
About the Author:
He works as a solution architect and developer, has more than 16 years of experience in software development on several platforms and more than 14 years only for the insurance market.