我采用了 Keith Jackson 的解决方案并将其修改为:
a) 使用 asp.net web api 2 - 属性路由以及老派路由
和
b) 不仅要验证路由参数名称,还要验证它们的值
例如对于以下路线
[HttpPost]
[Route("login")]
public HttpResponseMessage Login(string username, string password)
{
...
}
[HttpPost]
[Route("login/{username}/{password}")]
public HttpResponseMessage LoginWithDetails(string username, string password)
{
...
}
您可以验证路由匹配正确的 http 方法、控制器、操作和参数:
[TestMethod]
public void Verify_Routing_Rules()
{
"http://api.appname.com/account/login"
.ShouldMapTo<AccountController>("Login", HttpMethod.Post);
"http://api.appname.com/account/login/ben/password"
.ShouldMapTo<AccountController>(
"LoginWithDetails",
HttpMethod.Post,
new Dictionary<string, object> {
{ "username", "ben" }, { "password", "password" }
});
}
对 Keith Jackson 对Whyleee 解决方案的修改的修改。
public static class RoutingTestHelper
{
/// <summary>
/// Routes the request.
/// </summary>
/// <param name="config">The config.</param>
/// <param name="request">The request.</param>
/// <returns>Inbformation about the route.</returns>
public static RouteInfo RouteRequest(HttpConfiguration config, HttpRequestMessage request)
{
// create context
var controllerContext = new HttpControllerContext(config, new Mock<IHttpRouteData>().Object, request);
// get route data
var routeData = config.Routes.GetRouteData(request);
RemoveOptionalRoutingParameters(routeData.Values);
HttpActionDescriptor actionDescriptor = null;
HttpControllerDescriptor controllerDescriptor = null;
// Handle web api 2 attribute routes
if (routeData.Values.ContainsKey("MS_SubRoutes"))
{
var subroutes = (IEnumerable<IHttpRouteData>)routeData.Values["MS_SubRoutes"];
routeData = subroutes.First();
actionDescriptor = ((HttpActionDescriptor[])routeData.Route.DataTokens.First(token => token.Key == "actions").Value).First();
controllerDescriptor = actionDescriptor.ControllerDescriptor;
}
else
{
request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
controllerContext.RouteData = routeData;
// get controller type
controllerDescriptor = new DefaultHttpControllerSelector(config).SelectController(request);
controllerContext.ControllerDescriptor = controllerDescriptor;
// get action name
actionDescriptor = new ApiControllerActionSelector().SelectAction(controllerContext);
}
return new RouteInfo
{
Controller = controllerDescriptor.ControllerType,
Action = actionDescriptor.ActionName,
RouteData = routeData
};
}
#region | Extensions |
public static bool ShouldMapTo<TController>(this string fullDummyUrl, string action, Dictionary<string, object> parameters = null)
{
return ShouldMapTo<TController>(fullDummyUrl, action, HttpMethod.Get, parameters);
}
public static bool ShouldMapTo<TController>(this string fullDummyUrl, string action, HttpMethod httpMethod, Dictionary<string, object> parameters = null)
{
var request = new HttpRequestMessage(httpMethod, fullDummyUrl);
var config = new HttpConfiguration();
WebApiConfig.Register(config);
config.EnsureInitialized();
var route = RouteRequest(config, request);
var controllerName = typeof(TController).Name;
if (route.Controller.Name != controllerName)
throw new Exception(String.Format("The specified route '{0}' does not match the expected controller '{1}'", fullDummyUrl, controllerName));
if (route.Action.ToLowerInvariant() != action.ToLowerInvariant())
throw new Exception(String.Format("The specified route '{0}' does not match the expected action '{1}'", fullDummyUrl, action));
if (parameters != null && parameters.Any())
{
foreach (var param in parameters)
{
if (route.RouteData.Values.All(kvp => kvp.Key != param.Key))
throw new Exception(String.Format("The specified route '{0}' does not contain the expected parameter '{1}'", fullDummyUrl, param));
if (!route.RouteData.Values[param.Key].Equals(param.Value))
throw new Exception(String.Format("The specified route '{0}' with parameter '{1}' and value '{2}' does not equal does not match supplied value of '{3}'", fullDummyUrl, param.Key, route.RouteData.Values[param.Key], param.Value));
}
}
return true;
}
#endregion
#region | Private Methods |
/// <summary>
/// Removes the optional routing parameters.
/// </summary>
/// <param name="routeValues">The route values.</param>
private static void RemoveOptionalRoutingParameters(IDictionary<string, object> routeValues)
{
var optionalParams = routeValues
.Where(x => x.Value == RouteParameter.Optional)
.Select(x => x.Key)
.ToList();
foreach (var key in optionalParams)
{
routeValues.Remove(key);
}
}
#endregion
}
/// <summary>
/// Route information
/// </summary>
public class RouteInfo
{
public Type Controller { get; set; }
public string Action { get; set; }
public IHttpRouteData RouteData { get; set; }
}