2015-02-06 195 views
1

我犯了一個相當簡單的錯誤。在Fiddler中,我創建了一個POST。注意「FileFullpath」中,我使用了一個反斜槓而不是兩個。將NULL作爲參數傳遞給控制器​​POST方法

Fiddler POST

我的Web API模型的定義是這樣的...

public class GTMetadataModel 
{ 
    public int Id { get; set; } 

    public string ComputerId { get; set; } 
    public string UserId { get; set; } 
    public string FileFullpath { get; set; } 

    public string Version { get; set; } 
    public string[] Categories { get; set; } 
    public double[] Scores { get; set; } 
} 

我的Web API控制器的定義是這樣的...

public HttpResponseMessage PostGTMetadata(GTMetadataModel newentry) 
{ 
    ... // handle null parameter and return error here. 
    var response = Request.CreateResponse<GTMetadataModel>(HttpStatusCode.Created, newentry); 
    return response; 
} 

當我運行Web API併發送Fiddler POST,「newentry」爲空。花了一點時間才發現我需要兩個反斜槓。我將它改爲兩個,然後「newentry」是正確的。

因此,顯然問題是提供的數據不正確,但是我的服務器端代碼的位置和方式能夠檢測到不良的Json數據?

更新:馬克的答案被接受。因爲引用的帖子是一個健壯,優雅的方法的好例子。但是,對於那些只想簡單回答的人來說,引用的帖子使用「this.ModelState」來識別解析數據的問題。我可以將下面的代碼添加到我的Post處理程序方法中(更可能的是,我將從標記引用中回答某些問題)。

if(ModelState.IsValid == false) 
{ 
    var errors = ModelState 
     .Where(s => s.Value.Errors.Count > 0) 
     .Select(s => s.Key + ": " + s.Value.Errors.Select(t=>t.Exception.Message).Aggregate((a,b) => a + "\n" + b)) 
     .Aggregate((a, b) => a + "\n" + b); 
    Debug.Print(errors); 
    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, errors); 
} 
+0

馬上。你可以也應該驗證那個newentry不是null,並且它在對它執行任何敏感操作之前通過驗證。 – 2015-02-06 19:06:47

+0

這裏是有人用RexEx的東西 - http://stackoverflow.com/questions/25209757/how-can-i-detect-invalid-json-containing-a-trailing-comma-with-c – MethodMan 2015-02-06 19:06:52

+0

@DavidL - 是,我發現它是空的。但是,newentry已經被Web API框架解析,並且可能會失敗(爲了傳遞null)。我想檢測那裏的失敗,或至少訪問它對錯誤的評估。 – Les 2015-02-06 19:15:41

回答

0

您可以使用動作過濾器來攔截錯誤的請求。

見的問題,Validating parameters in ASP.NET Web API model binder

+0

@我將其標記爲答案。我喜歡這個解決方案,但是我更新了我的問題來給出答案的要點,即使用ModelState。 – Les 2015-02-06 20:47:28

相關問題