2014-03-31 29 views
2

在ASP.NET的的WebAPI,我怎么能保证复杂的操作参数总是被实例化?即使没有请求参数(在QueryString或POST主体中)。的Web API参数绑定回报情况,即使没有请求参数

例如,鉴于这一诱敌动作定义:

public IHttpActionResult GetBlahBlah(GetBlahBlahInput input) { .. } 

我想input永远是GetBlahBlahInput实例化的实例。默认行为是如果在请求的任何地方存在的请求参数,然后input不为空(即使没有请求参数都绑定到GetBlahBlahInput)。但是,如果没有参数发送,然后GetBlahBlahInputnull。我不想null,我想用参数的构造函数创建一个实例。

基本上,我想实现这个:

http://dotnet.dzone.com/articles/interesting-json-model-binding

在土地的WebAPI(所以没有DefaultModelBinder继承),我想它通用的,所以它可以处理任何输入类型。

我使用的WebAPI默认JsonMediaFormatter支持。

有什么想法?我很确定它可以完成,我可能会错过某个简单的配置步骤。

+0

你就不能简单的做一个 如果(输入== null)input = new GetBlahBlahInput();在方法的第一行?很简单,但也许我失去了一些东西 – PeterFromCologne

+0

不为我所需要的 - 我正在写将分配值输入模特属性的ActionFilterAttribute。所以这是Action实际触发之前(我重写了ActionExecuting())。如果我可以确定ActionFilterAttribute中的输入类型,我可以在那里处理它,但它感觉不对。正确的是ModelBinder总是返回一个实例化的对象。 – kdawg

+0

我明白你想要做什么。据我所知,WebAPI对原始类型使用ModelBinder,对复杂类型使用Formatter。我担心你最终会增加很多复杂性,试图强制某种没有打算的行为。我宁愿使用标准方式,并接受输入可能为空,如果它没有提供。对不起,我无能为力。 – PeterFromCologne

回答

0

如果我问了一下是可以做到,我仍然不知道。但作为的时候,这里是我在ActionFilterAttribute实施的解决方法(inputKey是参数的名称;在原来的问题是input):

// look for the "input" parameter and try to instantiate it and see if it implements the interface I'm interested in 
var parameterDescriptor = actionContext.ActionDescriptor.GetParameters().FirstOrDefault(p => string.Compare(p.ParameterName, inputKey, StringComparison.InvariantCultureIgnoreCase) == 0); 
if (parameterDescriptor == null 
    || (inputArgument = Activator.CreateInstance(parameterDescriptor.ParameterType) as IHasBlahBlahId) == null) 
{ 
    // if missing "input" parameter descriptor or it isn't an IHasBlahBlahId, then return unauthorized 
    actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); 
    return; 
} 

// otherwise, take that newly instantiated object and throw it into the ActionArguments! 
if (actionContext.ActionArguments.ContainsKey(inputKey)) 
    actionContext.ActionArguments[inputKey] = inputArgument; 
else 
    actionContext.ActionArguments.Add(inputKey, inputArgument); 
+0

你有没有找到另一种方法来做到这一点? – Marco

+0

不,我从来没有。但是我现在还没有在WebApi上编写将近一年半的时间,所以我已经失去了最新和最伟大的代码。 – kdawg

+0

公平的配偶,但一年半后最新最伟大的仍然是:P – Marco