我与MVC 4的Web API工作,我有这个虚拟ValueProvider:ValueProvider从来没有被称为
DummyValueProvider.cs
class DummyValueProvider : IValueProvider
{
public DummyValueProvider()
{
}
public bool ContainsPrefix(string prefix)
{
return true;
}
public ValueProviderResult GetValue(string key)
{
return new ValueProviderResult("testing", "testing", System.Globalization.CultureInfo.InvariantCulture);
}
}
class DummyValueProviderFactory : System.Web.Http.ValueProviders.ValueProviderFactory
{
public override IValueProvider GetValueProvider(System.Web.Http.Controllers.HttpActionContext actionContext)
{
return new DummyValueProvider();
}
}
这ValueProvider应该返回true
的要求任意键,因此在需要时它总是会为模型联编程序提供一个值。该ValueProvider注册在WebApiConfig这样的:
WebApiConfig.cs
config.Services.Add(typeof(ValueProviderFactory), new DummyValueProviderFactory());
代码编译和运行正常。 我也有在帐户API控制这个动作:
AccountController.cs
public HttpResponseMessage Register(string foo) { ... }
的行动被称为正常,当我把它象下面这样:
/register?foo=bar
而且foo
是按预期填写bar
;但如果我打电话:
/register
服务器返回404消息No HTTP resource was found that matches the request URI 'http://localhost:14459/register'
。
此外,我在方法ContainsPrefix()和GetValue()中放置断点,但它们永远不会被触发。
我在做什么错? DummyValueProvider不应该提供参数foo
的值testing
?
谢谢Cybermaxs,我已经阅读过你提到的文章。 关于你建议的测试,它按预期工作,并返回''foo''作为''testing'',即使我调用像''/ register''这样的API,调用我的值提供程序也没问题,而在查询中没有参数串。 不过,我不明白为什么调用''config.Services.Add()''没有触发值提供程序,正如您建议的那样。 –
我发现如果我用''public HttpResponseMessage Get([ModelBinder] string foo){...}''它也可以! 但我仍然无法理解为什么。 –
再次阅读这篇文章,我现在明白,如果你没有为简单类型指定绑定方法,它默认为''[FromUri]',并且值提供程序永远不会被调用。所以这就是我正在寻找的答案!我需要指定我想''[ModelBinder]''以便我的价值提供者可以被调用。 –