以上示例均不适用于我的个人需求。以下是我最终做的。
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 方法。那里的“真”表示我们要检查数组中项目的匹配。如果它是假的,你会说排除那些在 str 你可以使用高于此默认方法的路由,例如:
config.Routes.MapHttpRoute("GetStatus", "{controller}/status/{status}", new { action = "GetStatus" });
在上面它本质上是在寻找以下 URL =>http://www.domain.com/Account/Status/Active
或类似的东西。
除了上述之外,我不确定我会变得太疯狂。归根结底,它应该是每个资源。但我确实看到出于各种原因需要映射友好的 url。我很确定随着 Web Api 的发展,将会有某种规定。如果有时间,我会建立一个更永久的解决方案并发布。