我正在使用 ASP.NET WebAPI 构建 REST API。一切工作正常,但后来我想到了在所有方法调用中使用接口的好主意。更改所有方法后,我注意到将控制器方法中的参数设置为接口后,我的 API 调用不起作用。我正在使用 OWIN Self 主机和 Unity 依赖注入。这是我的相关代码:
解决我的界面:
IUnityContainer container = new UnityContainer();
container.RegisterType<IMyInterface, MyInterfaceImpl>(new HierarchicalLifetimeManager());
HttpConfiguration config = new HttpConfiguration();
config.DependencyResolver = new UnityDependencyResolver(container);
我的控制器(我收到错误的部分)
[Route("test")]
[HttpGet]
public HttpResponseMessage GetSomeData([FromUri]IMyInterface searchObject)
{
return this._searchService.SearchForData(searchObject);
}
调用此方法时,出现无法创建接口的错误。我理解这一点,但问题是解决它。我在看使用接口而不是具体类进行 ASP.NET Web API 操作 https://stackoverflow.com/questions/17119073/asp-net-web-api-operation-with-interfaces-instead-concrete-class并且也在https://brettedotnet.wordpress.com/2014/07/16/web-api-and-interface-parameters/ https://brettedotnet.wordpress.com/2014/07/16/web-api-and-interface-parameters/ and at 使用接口而不是具体类进行 ASP.NET Web API 操作 https://stackoverflow.com/questions/17119073/asp-net-web-api-operation-with-interfaces-instead-concrete-class,但这些建议都不适用于我的情况(总是收到无法创建接口的错误)。
我想知道是否有人有一个类似这样的工作示例(在 github 或其他地方)只是为了检查我做错了什么(或者甚至知道我还可以尝试什么会很好)
谢谢
因为您是从查询字符串传递数据,所以这里需要不同的方法。在您引用的我的博客文章中,我没有包含该场景。由于查询字符串是通过模型绑定器处理的,因此您需要创建一个自定义模型绑定器。
在我的情况下,我选择创建一个 IoCModelBinder,如下所示。
public class IocModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var targetObject = ServiceLocator.Current.GetInstance(bindingContext.ModelType);
var valueProvider = GlobalConfiguration.Configuration.Services.GetValueProviderFactories().First(item => item is QueryStringValueProviderFactory).GetValueProvider(actionContext);
foreach (var property in targetObject.GetType().GetProperties())
{
var valueAsString = valueProvider.GetValue(property.Name);
var value = valueAsString == null ? null : valueAsString.ConvertTo(property.PropertyType);
if (value == null)
continue;
property.SetValue(targetObject, value, null);
}
bindingContext.Model = targetObject;
return true;
}
}
并且在使用中
/// <summary>
/// Searches by the criteria specified.
/// </summary>
/// <param name="searchCriteriaDto">The search criteria dto.</param>
/// <returns></returns>
[HttpGet]
public HttpResponseMessage Search([ModelBinder(typeof(IocModelBinder))]IApplicationSearchCriteriaDto searchCriteriaDto)
{
}
希望这可以帮助。
Brette
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)