How can I provide a consistent URL between different controllers in an Asp.net MVC project?

C # interfaces are great for my controller management methods to take the same number, data type, and parameter order. Unfortunately, this does not help to match the URLs generated by the routing mechanism. How can I guarantee that the parameter names are the same?

For instance:

How to ensure that

sportswear/products 

and

 carsandtrucks/products 

both accept the productId parameter?

I would like to try to avoid the many routes in global.asax.cs since I feel that they are not intuitive, but I am open to ideas.

+4
source share
1 answer

I would suggest that the unit test is the best option, which will find all the implementations of the interfaces of your controller and ensure that the names of the implementation parameters match the names of the interface.

So something like

 public interface IController { ActionResult GetProducts(string productId); } [TestFixture] public class IControllerTest { [Test] public void EnsureImplementationsUseCorrectParameterNames() { // Assuming all required assemblies have been loaded var implementations = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes().Where(type => typeof(IController).IsAssignableFrom(type))); var interfaceMethods = typeof(IController).GetMethods().ToList(); foreach (var implementation in implementations) { var methodPairs = interfaceMethods.Join(implementation.GetMethods(), mi => mi.ToString(), mi => mi.ToString(), (inner, outer) => new { InterfaceMethod = inner, ImplementationMethod = outer }); foreach (var methodPair in methodPairs) { using (var interfaceParameters = methodPair.InterfaceMethod.GetParameters().Cast<ParameterInfo>().GetEnumerator()) using (var implementationParameters = methodPair.ImplementationMethod.GetParameters().Cast<ParameterInfo>().GetEnumerator()) { while (interfaceParameters.MoveNext() && implementationParameters.MoveNext()) { Assert.AreEqual(interfaceParameters.Current.Name, implementationParameters.Current.Name); } } } } } } 

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1379158/


All Articles