以上示例均无法满足我的个人需求。以下是我最终要做的事情。
public class ContainsConstraint : IHttpRouteConstraint
{
public string[] array { get; set; }
public bool match { get; set; }
/// <summary>
/// Check if param contains any of values listed in array.
/// </summary>
/// <param name="param">The param to test.</param>
/// <param name="array">The items to compare against.</param>
/// <param name="match">Whether we are matching or NOT matching.</param>
public ContainsConstraint(string[] array, bool match)
{
this.array = array;
this.match = match;
}
public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
if (values == null) // shouldn't ever hit this.
return true;
if (!values.ContainsKey(parameterName)) // make sure the parameter is there.
return true;
if (string.IsNullOrEmpty(values[parameterName].ToString())) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
values[parameterName] = request.Method.ToString();
bool contains = array.Contains(values[parameterName]); // this is an extension but all we are doing here is check if string array contains value you can create exten like this or use LINQ or whatever u like.
if (contains == match) // checking if we want it to match or we don't want it to match
return true;
return false;
}
要在路线中使用以上内容,请使用:
config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { action = RouteParameter.Optional, id = RouteParameter.Optional}, new { action = new ContainsConstraint( new string[] { "GET", "PUT", "DELETE", "POST" }, true) });
发生的是方法中的约束种类伪造品,因此此路由将仅与默认的GET,POST,PUT和DELETE方法匹配。此处的“ true”表示我们要检查数组中各项的匹配情况。如果为假,则表示要排除str中的那些。然后,您可以在此默认方法之上使用路由,例如:
config.Routes.MapHttpRoute("GetStatus", "{controller}/status/{status}", new { action = "GetStatus" });
在上面,它实际上是在寻找以下URL => http://www.domain.com/Account/Status/Active
或类似的东西。
除了以上所述,我不确定我会变得太疯狂了。在一天结束时,应该针对每个资源。但是我确实出于各种原因需要映射友好的URL。随着Web Api的发展,我可以肯定会有一些规定。如果有时间的话,我将建立一个更永久的解决方案并发布。