2014-03-31 30 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