Use of Model Binder in MVC and Web API
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
FSL.ModelBinderInMvcAndWebApi
.gitignore
FSL.ModelBinderInMvcAndWebApi.sln
LICENSE
README.md

README.md

FSL.ModelBinderInMvcAndWebApi

Use of Model Binder in MVC and Web API

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

enter image description here

FULL ARTICLE:

English: https://fabiosilvalima.net/en/use-model-binder-mvc-web-api/

Português: https://fabiosilvalima.net/uso-de-model-binder-no-mvc-e-web-api/


What is in the source code?

FSL.ModelBinderInMvcAndWebApi

  • Visual Studio solution file;
  • MVC and Web API application from .NET template;
  • Classes for our solution;

Remarks:

  • I created the application using the Web Application template and I have checked MVC and Web API checkboxes. Visual Studio created a lot of files, views, scripts. I do not use them. Let's concentrate just the model binders.

What is the goal?

I have a lot information of environment like logged user id, requested url, frontend id, credentials, browser info and so on. Some those information may or not be in the fronend form*

  • Will be available here in next version.

Assumptions:

  • The model binder class must work in both MVC and Web Api controllers;
  • I do not want to explicit call those environment info as a local variable.

Explaining...

Binders/EnvironmentInfoModelBinder.cs

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";
        }
    }

Services/Controllers/PersonApiController.cs

[RoutePrefix("api/person")]
    public class PersonApiController : ApiController
    {
        [Route("")]
        public IHttpActionResult Get(Models.EnvironmentInfo environmentInfo)
        {
            var result = new
            {
                EnvironmentInfo = environmentInfo
            };

            return Ok(result);
        }
    }

Controller/HomeController.cs

public class HomeController : Controller
    {
        public ActionResult Index(Models.EnvironmentInfo environmentInfo)
        {
            return View();
        }
    }

Global.asax.cs

protected void Application_Start()
        {
            // MVC model binder version
                        ModelBinders.Binders.Add(typeof(Models.EnvironmentInfo), new Binders.EnvironmentInfoModelBinder());
                        
        }

App_Start/WebApiConfig.cs

public static void Register(HttpConfiguration config)
        {
            // Web API model binder version

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

References:

Licence:

  • [Licence MIT][4]