"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Working with the Application Model

By Steve Smith

ASP.NET Core MVC defines an application model representing the components of an MVC app. You can read and manipulate this model to modify how MVC elements behave. By default, MVC follows certain conventions to determine which classes are considered to be controllers, which methods on those classes are actions, and how parameters and routing behave. You can customize this behavior to suit your app’s needs by creating your own conventions and applying them globally or as attributes.

Models and Providers

The ASP.NET Core MVC application model include both abstract interfaces and concrete implementation classes that describe an MVC application. This model is the result of MVC discovering the app’s controllers, actions, action parameters, routes, and filters according to default conventions. By working with the application model, you can modify your app to follow different conventions from the default MVC behavior. The parameters, names, routes, and filters are all used as configuration data for actions and controllers.

The ASP.NET Core MVC Application Model has the following structure:

Each level of the model has access to a common Properties collection, and lower levels can access and overwrite property values set by higher levels in the hierarchy. The properties are persisted to the ActionDescriptor.Properties when the actions are created. Then when a request is being handled, any properties a convention added or modified can be accessed through ActionContext.ActionDescriptor.Properties. Using properties is a great way to configure your filters, model binders, etc. on a per-action basis.

[!NOTE] The ActionDescriptor.Properties collection is not thread safe (for writes) once app startup has finished. Conventions are the best way to safely add data to this collection.

IApplicationModelProvider

ASP.NET Core MVC loads the application model using a provider pattern, defined by the IApplicationModelProvider interface. This section covers some of the internal implementation details of how this provider functions. This is an advanced topic - most apps that leverage the application model should do so by working with conventions.

Implementations of the IApplicationModelProvider interface “wrap” one another, with each implementation calling OnProvidersExecuting in ascending order based on its Order property. The OnProvidersExecuted method is then called in reverse order. The framework defines several providers:

First (Order=-1000):

Then (Order=-990):

[!NOTE] The order in which two providers with the same value for Order are called is undefined, and therefore should not be relied upon.

[!NOTE] IApplicationModelProvider is an advanced concept for framework authors to extend. In general, apps should use conventions and frameworks should use providers. The key distinction is that providers always run before conventions.

The DefaultApplicationModelProvider establishes many of the default behaviors used by ASP.NET Core MVC. Its responsibilities include:

Some built-in behaviors are implemented by the DefaultApplicationModelProvider. This provider is responsible for constructing the ControllerModel, which in turn references ActionModel, PropertyModel, and ParameterModel instances. The DefaultApplicationModelProvider class is an internal framework implementation detail that can and will change in the future.

The AuthorizationApplicationModelProvider is responsible for applying the behavior associated with the AuthorizeFilter and AllowAnonymousFilter attributes. (xref:)Learn more about these attributes.

The CorsApplicationModelProvider implements behavior associated with the IEnableCorsAttribute and IDisableCorsAttribute, and the DisableCorsAuthorizationFilter. (xref:)Learn more about CORS.

Conventions

The application model defines convention abstractions that provide a simpler way to customize the behavior of the models than overriding the entire model or provider. These abstractions are the recommended way to modify your app’s behavior. Conventions provide a way for you to write code that will dynamically apply customizations. While (xref:)filters provide a means of modifying the framework’s behavior, customizations let you control how the whole app is wired together.

The following conventions are available:

Conventions are applied by adding them to MVC options or by implementing Attributes and applying them to controllers, actions, or action parameters (similar to (xref:)Filters). Unlike filters, conventions are only executed when the app is starting, not as part of each request.

Sample: Modifying the ApplicationModel

The following convention is used to add a property to the application model.

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc.ApplicationModels;
   2:   
   3:  namespace AppModelSample.Conventions
   4:  {
   5:      public class ApplicationDescription : IApplicationModelConvention
   6:      {
   7:          private readonly string _description;
   8:   
   9:          public ApplicationDescription(string description)
  10:          {
  11:              _description = description;
  12:          }
  13:   
  14:          public void Apply(ApplicationModel application)
  15:          {
  16:              application.Properties["description"] = _description;
  17:          }
  18:      }
  19:  }

Application model conventions are applied as options when MVC is added in ConfigureServices in Startup.

[!code-csharpMain]

   1:  using AppModelSample.Conventions;
   2:  using Microsoft.AspNetCore.Builder;
   3:  using Microsoft.AspNetCore.Hosting;
   4:  using Microsoft.Extensions.Configuration;
   5:  using Microsoft.Extensions.DependencyInjection;
   6:  using Microsoft.Extensions.Logging;
   7:   
   8:  namespace AppModelSample
   9:  {
  10:      public class Startup
  11:      {
  12:          public Startup(IHostingEnvironment env)
  13:          {
  14:              var builder = new ConfigurationBuilder()
  15:                  .SetBasePath(env.ContentRootPath)
  16:                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  17:                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
  18:                  .AddEnvironmentVariables();
  19:              Configuration = builder.Build();
  20:          }
  21:   
  22:          public IConfigurationRoot Configuration { get; }
  23:   
  24:          // This method gets called by the runtime. Use this method to add services to the container.
  25:          #region ConfigureServices
  26:          public void ConfigureServices(IServiceCollection services)
  27:          {
  28:              services.AddMvc(options =>
  29:              {
  30:                  options.Conventions.Add(new ApplicationDescription("My Application Description"));
  31:                  options.Conventions.Add(new NamespaceRoutingConvention());
  32:                  //options.Conventions.Add(new IdsMustBeInRouteParameterModelConvention());
  33:              });
  34:          }
  35:          #endregion
  36:   
  37:          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  38:          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  39:          {
  40:              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  41:              loggerFactory.AddDebug();
  42:   
  43:              if (env.IsDevelopment())
  44:              {
  45:                  app.UseDeveloperExceptionPage();
  46:                  app.UseBrowserLink();
  47:              }
  48:              else
  49:              {
  50:                  app.UseExceptionHandler("/Home/Error");
  51:              }
  52:   
  53:              app.UseStaticFiles();
  54:   
  55:              app.UseMvc(routes =>
  56:              {
  57:                  routes.MapRoute(
  58:                      name: "default",
  59:                      template: "{controller=Home}/{action=Index}/{id?}");
  60:              });
  61:          }
  62:      }
  63:  }

Properties are accessible from the ActionDescriptor properties collection within controller actions:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc;
   2:   
   3:  namespace AppModelSample.Controllers
   4:  {
   5:      #region AppModelController
   6:      public class AppModelController : Controller
   7:      {
   8:          public string Description()
   9:          {
  10:              return "Description: " + ControllerContext.ActionDescriptor.Properties["description"];
  11:          }
  12:      }
  13:      #endregion
  14:  }

Sample: Modifying the ControllerModel Description

As in the previous example, the controller model can also be modified to include custom properties. These will override existing properties with the same name specified in the application model. The following convention attribute adds a description at the controller level:

[!code-csharpMain]

   1:  using System;
   2:  using Microsoft.AspNetCore.Mvc.ApplicationModels;
   3:   
   4:  namespace AppModelSample.Conventions
   5:  {
   6:      public class ControllerDescriptionAttribute : Attribute, IControllerModelConvention
   7:      {
   8:          private readonly string _description;
   9:   
  10:          public ControllerDescriptionAttribute(string description)
  11:          {
  12:              _description = description;
  13:          }
  14:   
  15:          public void Apply(ControllerModel controllerModel)
  16:          {
  17:              controllerModel.Properties["description"] = _description;
  18:          }
  19:      }
  20:  }

This convention is applied as an attribute on a controller.

[!code-csharpMain]

   1:  using AppModelSample.Conventions;
   2:  using Microsoft.AspNetCore.Mvc;
   3:   
   4:  namespace AppModelSample.Controllers
   5:  {
   6:      #region DescriptionAttributesController
   7:      #region ControllerDescription
   8:      [ControllerDescription("Controller Description")]
   9:      public class DescriptionAttributesController : Controller
  10:      {
  11:          public string Index()
  12:          {
  13:              return "Description: " + ControllerContext.ActionDescriptor.Properties["description"];
  14:          }
  15:          #endregion
  16:   
  17:          [ActionDescription("Action Description")]
  18:          public string UseActionDescriptionAttribute()
  19:          {
  20:              return "Description: " + ControllerContext.ActionDescriptor.Properties["description"];
  21:          }
  22:      }
  23:      #endregion
  24:  }

The “description” property is accessed in the same manner as in previous examples.

Sample: Modifying the ActionModel Description

A separate attribute convention can be applied to individual actions, overriding behavior already applied at the application or controller level.

[!code-csharpMain]

   1:  using System;
   2:  using Microsoft.AspNetCore.Mvc.ApplicationModels;
   3:   
   4:  namespace AppModelSample.Conventions
   5:  {
   6:      public class ActionDescriptionAttribute : Attribute, IActionModelConvention
   7:      {
   8:          private readonly string _description;
   9:   
  10:          public ActionDescriptionAttribute(string description)
  11:          {
  12:              _description = description;
  13:          }
  14:   
  15:          public void Apply(ActionModel actionModel)
  16:          {
  17:              actionModel.Properties["description"] = _description;
  18:          }
  19:      }
  20:  }

Applying this to an action within the previous example’s controller demonstrates how it overrides the controller-level convention:

[!code-csharpMain]

   1:  using AppModelSample.Conventions;
   2:  using Microsoft.AspNetCore.Mvc;
   3:   
   4:  namespace AppModelSample.Controllers
   5:  {
   6:      #region DescriptionAttributesController
   7:      #region ControllerDescription
   8:      [ControllerDescription("Controller Description")]
   9:      public class DescriptionAttributesController : Controller
  10:      {
  11:          public string Index()
  12:          {
  13:              return "Description: " + ControllerContext.ActionDescriptor.Properties["description"];
  14:          }
  15:          #endregion
  16:   
  17:          [ActionDescription("Action Description")]
  18:          public string UseActionDescriptionAttribute()
  19:          {
  20:              return "Description: " + ControllerContext.ActionDescriptor.Properties["description"];
  21:          }
  22:      }
  23:      #endregion
  24:  }

Sample: Modifying the ParameterModel

The following convention can be applied to action parameters to modify their BindingInfo. The following convention requires that the parameter be a route parameter; other potential binding sources (such as query string values) are ignored.

[!code-csharpMain]

   1:  using System;
   2:  using Microsoft.AspNetCore.Mvc.ApplicationModels;
   3:  using Microsoft.AspNetCore.Mvc.ModelBinding;
   4:   
   5:  namespace AppModelSample.Conventions
   6:  {
   7:      public class MustBeInRouteParameterModelConvention : Attribute, IParameterModelConvention
   8:      {
   9:          public void Apply(ParameterModel model)
  10:          {
  11:              if (model.BindingInfo == null)
  12:              {
  13:                  model.BindingInfo = new BindingInfo();
  14:              }
  15:              model.BindingInfo.BindingSource = BindingSource.Path;
  16:          }
  17:      }
  18:  }

The attribute may be applied to any action parameter:

[!code-csharpMain]

   1:  using AppModelSample.Conventions;
   2:  using Microsoft.AspNetCore.Mvc;
   3:   
   4:  namespace AppModelSample.Controllers
   5:  {
   6:      #region ParameterModelController
   7:      public class ParameterModelController : Controller
   8:      {
   9:          // Will bind:  /ParameterModel/GetById/123
  10:          // WON'T bind: /ParameterModel/GetById?id=123
  11:          public string GetById([MustBeInRouteParameterModelConvention]int id)
  12:          {
  13:              return $"Bound to id: {id}";
  14:          }
  15:      }
  16:      #endregion
  17:  }

Sample: Modifying the ActionModel Name

The following convention modifies the ActionModel to update the name of the action to which it is applied. The new name is provided as a parameter to the attribute. This new name is used by routing, so it will affect the route used to reach this action method.

[!code-csharpMain]

   1:  using System;
   2:  using Microsoft.AspNetCore.Mvc.ApplicationModels;
   3:   
   4:  namespace AppModelSample.Conventions
   5:  {
   6:      public class CustomActionNameAttribute : Attribute, IActionModelConvention
   7:      {
   8:          private readonly string _actionName;
   9:   
  10:          public CustomActionNameAttribute(string actionName)
  11:          {
  12:              _actionName = actionName;
  13:          }
  14:   
  15:          public void Apply(ActionModel actionModel)
  16:          {
  17:              // this name will be used by routing
  18:              actionModel.ActionName = _actionName;
  19:          }
  20:      }
  21:  }

This attribute is applied to an action method in the HomeController:

[!code-csharpMain]

   1:  using AppModelSample.Conventions;
   2:  using Microsoft.AspNetCore.Mvc;
   3:   
   4:  namespace AppModelSample.Controllers
   5:  {
   6:      public class HomeController : Controller
   7:      {
   8:          public IActionResult Index()
   9:          {
  10:              return View();
  11:          }
  12:   
  13:          #region ActionModelConvention
  14:          // Route: /Home/MyCoolAction
  15:          [CustomActionName("MyCoolAction")]
  16:          public string SomeName()
  17:          {
  18:              return ControllerContext.ActionDescriptor.ActionName;
  19:          }
  20:          #endregion
  21:      }
  22:  }

Even though the method name is SomeName, the attribute overrides the MVC convention of using the method name and replaces the action name with MyCoolAction. Thus, the route used to reach this action is /Home/MyCoolAction.

[!NOTE] This example is essentially the same as using the built-in ActionName attribute.

Sample: Custom Routing Convention

You can use an IApplicationModelConvention to customize how routing works. For example, the following convention will incorporate Controllers’ namespaces into their routes, replacing . in the namespace with / in the route:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc.ApplicationModels;
   2:  using System.Linq;
   3:   
   4:  namespace AppModelSample.Conventions
   5:  {
   6:      public class NamespaceRoutingConvention : IApplicationModelConvention
   7:      {
   8:          public void Apply(ApplicationModel application)
   9:          {
  10:              foreach (var controller in application.Controllers)
  11:              {
  12:                  var hasAttributeRouteModels = controller.Selectors
  13:                      .Any(selector => selector.AttributeRouteModel != null);
  14:   
  15:                  if (!hasAttributeRouteModels
  16:                      && controller.ControllerName.Contains("Namespace")) // affect one controller in this sample
  17:                  {
  18:                      // Replace the . in the namespace with a / to create the attribute route
  19:                      // Ex: MySite.Admin namespace will correspond to MySite/Admin attribute route
  20:                      // Then attach [controller], [action] and optional {id?} token.
  21:                      // [Controller] and [action] is replaced with the controller and action
  22:                      // name to generate the final template
  23:                      controller.Selectors[0].AttributeRouteModel = new AttributeRouteModel()
  24:                      {
  25:                          Template = controller.ControllerType.Namespace.Replace('.', '/') + "/[controller]/[action]/{id?}"
  26:                      };
  27:                  }
  28:              }
  29:   
  30:              // You can continue to put attribute route templates for the controller actions depending on the way you want them to behave
  31:          }
  32:      }
  33:  }

The convention is added as an option in Startup.

[!code-csharpMain]

   1:  using AppModelSample.Conventions;
   2:  using Microsoft.AspNetCore.Builder;
   3:  using Microsoft.AspNetCore.Hosting;
   4:  using Microsoft.Extensions.Configuration;
   5:  using Microsoft.Extensions.DependencyInjection;
   6:  using Microsoft.Extensions.Logging;
   7:   
   8:  namespace AppModelSample
   9:  {
  10:      public class Startup
  11:      {
  12:          public Startup(IHostingEnvironment env)
  13:          {
  14:              var builder = new ConfigurationBuilder()
  15:                  .SetBasePath(env.ContentRootPath)
  16:                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  17:                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
  18:                  .AddEnvironmentVariables();
  19:              Configuration = builder.Build();
  20:          }
  21:   
  22:          public IConfigurationRoot Configuration { get; }
  23:   
  24:          // This method gets called by the runtime. Use this method to add services to the container.
  25:          #region ConfigureServices
  26:          public void ConfigureServices(IServiceCollection services)
  27:          {
  28:              services.AddMvc(options =>
  29:              {
  30:                  options.Conventions.Add(new ApplicationDescription("My Application Description"));
  31:                  options.Conventions.Add(new NamespaceRoutingConvention());
  32:                  //options.Conventions.Add(new IdsMustBeInRouteParameterModelConvention());
  33:              });
  34:          }
  35:          #endregion
  36:   
  37:          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  38:          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  39:          {
  40:              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  41:              loggerFactory.AddDebug();
  42:   
  43:              if (env.IsDevelopment())
  44:              {
  45:                  app.UseDeveloperExceptionPage();
  46:                  app.UseBrowserLink();
  47:              }
  48:              else
  49:              {
  50:                  app.UseExceptionHandler("/Home/Error");
  51:              }
  52:   
  53:              app.UseStaticFiles();
  54:   
  55:              app.UseMvc(routes =>
  56:              {
  57:                  routes.MapRoute(
  58:                      name: "default",
  59:                      template: "{controller=Home}/{action=Index}/{id?}");
  60:              });
  61:          }
  62:      }
  63:  }

[!TIP] You can add conventions to your (xref:)middleware by accessing MvcOptions using services.Configure<MvcOptions>(c => c.Conventions.Add(YOURCONVENTION));

This sample applies this convention to routes that are not using attribute routing where the controller has “Namespace” in its name. The following controller demonstrates this convention:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc;
   2:   
   3:  namespace AppModelSample.Controllers
   4:  {
   5:      public class NamespaceRoutingController : Controller
   6:      {
   7:          // using NamespaceRoutingConvention
   8:          // route: /AppModelSample/Controllers/NamespaceRouting/Index
   9:          public string Index()
  10:          {
  11:              return "This demonstrates namespace routing.";
  12:          }
  13:      }
  14:  }

Application Model Usage in WebApiCompatShim

ASP.NET Core MVC uses a different set of conventions from ASP.NET Web API 2. Using custom conventions, you can modify an ASP.NET Core MVC app’s behavior to be consistent with that of a Web API app. Microsoft ships the WebApiCompatShim specifically for this purpose.

[!NOTE] Learn more about (xref:)migrating from ASP.NET Web API.

To use the Web API Compatibility Shim, you need to add the package to your project and then add the conventions to MVC by calling AddWebApiConventions in Startup:

The conventions provided by the shim are only applied to parts of the app that have had certain attributes applied to them. The following four attributes are used to control which controllers should have their conventions modified by the shim’s conventions:

Action Conventions

The UseWebApiActionConventionsAttribute is used to map the HTTP method to actions based on their name (for instance, Get would map to HttpGet). It only applies to actions that do not use attribute routing.

Overloading

The UseWebApiOverloadingAttribute is used to apply the WebApiOverloadingApplicationModelConvention convention. This convention adds an OverloadActionConstraint to the action selection process, which limits candidate actions to those for which the request satisfies all non-optional parameters.

Parameter Conventions

The UseWebApiParameterConventionsAttribute is used to apply the WebApiParameterConventionsApplicationModelConvention action convention. This convention specifies that simple types used as action parameters are bound from the URI by default, while complex types are bound from the request body.

Routes

The UseWebApiRoutesAttribute controls whether the WebApiApplicationModelConvention controller convention is applied. When enabled, this convention is used to add support for (xref:)areas to the route.

In addition to a set of conventions, the compatibility package includes a System.Web.Http.ApiController base class that replaces the one provided by Web API. This allows your controllers written for Web API and inheriting from its ApiController to work as they were designed, while running on ASP.NET Core MVC. This base controller class is decorated with all of the UseWebApi* attributes listed above. The ApiController exposes properties, methods, and result types that are compatible with those found in Web API.

Using ApiExplorer to Document Your App

The application model exposes an ApiExplorer property at each level that can be used to traverse the app’s structure. This can be used to generate help pages for your Web APIs using tools like Swagger. The ApiExplorer property exposes an IsVisible property that can be set to specify which parts of your app’s model should be exposed. You can configure this setting using a convention:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc.ApplicationModels;
   2:   
   3:  namespace AppModelSample.Conventions
   4:  {
   5:      public class EnableApiExplorerApplicationConvention : IApplicationModelConvention
   6:      {
   7:          public void Apply(ApplicationModel application)
   8:          {
   9:              application.ApiExplorer.IsVisible = true;
  10:          }
  11:      }
  12:  }

Using this approach (and additional conventions if required), you can enable or disable API visibility at any level within your app.





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnetcore/mvc/controllers/application-model.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>