REST WebAPI接口作为API调用中的参数 [英] REST WebAPI Interface as parameter in API Call

查看:218
本文介绍了REST WebAPI接口作为API调用中的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET WebAPI构建REST API。一切正常,但是后来我想到了在所有方法调用中使用接口的好主意。更改所有方法后,我注意到在将Controller方法中的参数设置为接口后,我的API调用不起作用。我正在使用OWIN Self主机和Unity依赖项注入。这是我的相关代码:

I am building a REST API with ASP.NET WebAPI. Everything worked fine, but then I came up with the great idea to use interfaces in all my method calls. After I have changed all the methods i noticed that after setting the parameter in my Controller methods as interfaces, my API calls does not work. I am using OWIN Self host and Unity dependency injection. Here is my relevant code:

解析我的界面:

      IUnityContainer container = new UnityContainer();

      container.RegisterType<IMyInterface, MyInterfaceImpl>(new HierarchicalLifetimeManager());
      HttpConfiguration config = new HttpConfiguration();
      config.DependencyResolver = new UnityDependencyResolver(container);  

我的控制器(我收到错误的部分)

My Controller (the part where i get the error)

    [Route("test")]
    [HttpGet]
    public HttpResponseMessage GetSomeData([FromUri]IMyInterface searchObject)
    {
         return this._searchService.SearchForData(searchObject);

    }

调用此方法时,我得到一个错误,即接口无法被创建。我不理解,但是问题正在解决。我看了使用接口的ASP.NET Web API操作具体类以及 https: //brettedotnet.wordpress.com/2014/07/16/web-api-and-interface-parameters/ 使用接口而不是具体类的ASP.NET Web API操作,但在我的情况下,这些建议均无用(总是得到这样的错误:接口无法创建)。

When calling this method i get the error that an interface cannot be created. I unterstand that, but the problem is fixing it. I looked at ASP.NET Web API Operation with interfaces instead concrete class and also at https://brettedotnet.wordpress.com/2014/07/16/web-api-and-interface-parameters/ and at ASP.NET Web API Operation with interfaces instead concrete class, but none of the suggestions worked in my case (always getting the error that an interface cannot be created).

我想知道是否有人在github或其他地方有类似这样的工作示例,只是为了检查我做错了什么(甚至是一个主意)可以尝试一下会很好)

I was wondering if someone has a working example on something like this(on github or elsewhere) just to check what I am doing wrong (or even an idea what else I could try would be nice)

谢谢

推荐答案

因为您从查询字符串传递数据,这里需要一种不同的方法。在您引用的博客文章中,我没有提到这种情况。由于查询字符串是通过模型绑定器处理的,因此您需要创建自定义模型绑定器。

Because you are passing data from the querystring a different approach is required here. In my blog post that you referenced I did not include that scenario. Since querystrings are handled via Model Binders you need to create a custom model binder.

在我的情况下,我选择创建一个IoCModelBinder,如下所示。

In my situation I opted for creating a IoCModelBinder as seen below.

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

这篇关于REST WebAPI接口作为API调用中的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆