网页API参数,即使没有请求参数绑定回报实例 [英] Web API Parameter Binding return instance even without request parameters
问题描述
使用ASP.NET的的WebAPI,我怎么能保证复杂的操作参数将永远被实例化?甚至在没有请求的参数(在查询字符串或POST体)。
With ASP.NET's WebApi, How can I assure that a complex Action parameter will always be instantiated? Even in the absence of request parameters (in the QueryString or POST body).
例如,鉴于这一虚拟操作定义:
For example, given this dummy action definition:
public IHttpActionResult GetBlahBlah(GetBlahBlahInput input) { .. }
我想输入
永远是 GetBlahBlahInput
的一个实例化的实例。默认行为是,如果在请求中的任何地方存在的请求参数,那么输入
不为空(即使没有请求参数都绑定到 GetBlahBlahInput
)。但是,如果没有参数发送,那么 GetBlahBlahInput
是空
。我不想空
,我想用参数的构造函数创建一个实例。
I want input
to always be an instantiated instance of GetBlahBlahInput
. Default behavior is if request parameters exist anywhere in the request, then input
is not null (even if none of the request parameters are bindable to GetBlahBlahInput
.) However, if no parameters are sent, then GetBlahBlahInput
is null
. I don't want null
, I want an instance created with the parameterless constructor.
基本上,我想实现这个:
Basically, I'm trying to implement this:
http://dotnet.dzone.com/articles/interesting-json-模型结合
在土地的WebAPI(所以没有 DefaultModelBinder
继承),我希望它通用的,所以它可以处理任何输入类型。
In WebApi land (so no DefaultModelBinder
inheritance) and I want it generic, so it can handle any input type.
我使用的WebAPI默认JsonMediaFormatter支持。
I'm using the default JsonMediaFormatter support in WebApi.
有什么想法?我是pretty肯定是可以做到的,我可能是某处缺少一个简单的配置步骤。
Any thoughts? I'm pretty sure it can be done and I may be missing a simple configuration step somewhere.
推荐答案
我还在想,如果我问起可以做到的。但作为的时候,这里是我在ActionFilterAttribute实施( inputKey
是参数的名称的解决办法;在原来的问题是输入
)
I'm still wondering if what I asked about can be done. But for the time being, here's the workaround I implemented in my ActionFilterAttribute (inputKey
is the name of the parameter; in the original question it's 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);
这篇关于网页API参数,即使没有请求参数绑定回报实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!