如果您看到 source code ,您会注意到值不是字符串的单元测试(例如 BindValuesAsync_RouteData_Values_To_Simple_Types)。
你说你在写一个自定义约束,让我们来看看这个:
public class MyConstraint : IHttpRouteConstraint
{
public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
string parameters = string.Join(Environment.NewLine, values.Select(p => p.Value.GetType().FullName).ToArray());
return true;
}
}
你注册它:
config.Routes.MapHttpRoute("DefaultApi",
"api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional },
new { isLocal = new MyConstraint() });
假设你有这个控制器:
public class ValuesController : ApiController
{
public string Get(int id) { return "Value"; }
}
如果您向“/api/values/Get/1”发出 GET 请求,您会注意到值的类型
- System.String //值
- System.String //获取
- System.String //1
但是
如果您向“/api/values/1”发出 GET 请求,您会注意到值的类型
- System.String //值
- System.String //1
- System.Web.Http.RouteParameter
如果你看到source code of the class
/// <summary>
/// The <see cref="RouteParameter"/> class can be used to indicate properties about a route parameter (the literals and placeholders
/// located within segments of a <see cref="M:IHttpRoute.RouteTemplate"/>).
/// It can for example be used to indicate that a route parameter is optional.
/// </summary>
public sealed class RouteParameter
{
public static readonly RouteParameter Optional = new RouteParameter();
// singleton constructor
private RouteParameter() { }
public override string ToString() { return string.Empty; }
}
因此,当您不提供可选参数时,有时这不是字符串。
您应该首先检查对象的类型,只有当它是非空字符串时,才尝试解析它