如何在Web Api中的Json / Xml请求中检测发布,过度发布和错误请求 [英] How Do I Detect Under Posting, Over Posting And Bad Request In Json/Xml Request In Web Api Asp.Net
问题描述
我在xml或json中有一个请求。如何检查请求是否包含缺失的正文或无效的正文项。
i have a request in xml or json. How can i check whether the request contain a missing body or invalid body item.
content-type:application/json;
Method:Post;
{"UserName":"tom12","Password":"XXXXXXXXX","FirstName":"tom","LastName":"jack", "MiddleName":"dick"}
他们可能在输入中缺少MiddleName,即输入可能是格式
their may be MiddleName missing int the input, i.e input may be in the form
{"UserName":"tom12","Password":"XXXXXXXXX","FirstName":"tom","LastName":"jack" }
这里我想检测输入错误并显示消息错误的请求格式 - 有些东西丢失了
或者,
2)有时他们可能会输入中的一些额外字段
Here i want to detect the error on input and display the message "Bad Request Format -- Something is Missing"
Or,
2) sometime their may be some extra field in the input
{"UserName":"Jeff Henry", "Password":"XXXXXXXXX","FirstName":"Jeff","LastName":"Henry","MiddleName":"ok","Email":"abc@email.com" }
Here i want to detect the error on input and display the message "Bad Request Format"
3) the FirstName and LastName are Required Field in the model, but they are empty i.e
{"UserName":"Jeff Henry", "Password":"XXXXXXXXX","FirstName":"","LastName":"","MiddleName":"ok"}
这里我想检测错误并显示消息RequiredFieldMissing
我的控制器:
here i want to detect the error and display message "RequiredFieldMissing"
My Controller:
public HttpResponseMessage Post(User user, HttpRequestMessage request)
{
if (ModelState.IsValid)
{
// insrt.Insert(user);
}
else
{
//Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid model.");
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
型号:
Models:
Public class User
{
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
}
推荐答案
如果您对字段进行了必需的验证,那么它将不会发布&安培;除非您填写其中的值。所以,这可以消除你的问题。
如果你没有指定任何验证,你可以这样做:
If you have Required Validation on fields, then it won't be posted until & unless you fill values in it. So, that eliminates your issue.
And if you haven't specify any validation, you can do this:
string errorMessage = string.empty;
public HttpResponseMessage Post(User user, HttpRequestMessage request)
{
if (ModelState.IsValid)
{
// insrt.Insert(user);
if(string.IsEmptyOrNull(user.MiddleName))
{
errorMessage = "Middle Name is missing"
}
else if(string.IsEmptyOrNull(user.Email))
{
errorMessage = "Email is missing"
}
else if(condition for another property){
// set the errorMessage....
}
}
else
{
//Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid model.");
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
希望这就是你想要的。
-KR
Hope this is what you want.
-KR
这篇关于如何在Web Api中的Json / Xml请求中检测发布,过度发布和错误请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!