我犯了一个相当简单的错误。在Fiddler中,我创建了一个POST。注意“FileFullpath”中,我使用了一个反斜杠而不是两个。将NULL作为参数传递给控制器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);
}
马上。你可以也应该验证那个newentry不是null,并且它在对它执行任何敏感操作之前通过验证。 – 2015-02-06 19:06:47
这里是有人用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
@DavidL - 是,我发现它是空的。但是,newentry已经被Web API框架解析,并且可能会失败(为了传递null)。我想检测那里的失败,或至少访问它对错误的评估。 – Les 2015-02-06 19:15:41