如何从web api发送带有验证的模型2 c#

时间:2016-03-16 05:10:12

标签: c# asp.net asp.net-web-api asp.net-web-api2

我正在研究Asp.net WebApi2,我想将模型+验证发送给客户端。因为那时验证客户端应用程序可以进行这些验证。

我可以通过创建类

来验证客户端应用程序发送的数据
public class CalibrationEntity : BaseEntity
{
    [Required(AllowEmptyStrings = false)]        
    [RegularExpression(@"\d{0,3}", ErrorMessage = "The calno field must be in format XXX")]
    public string calno { get; set; }

    [Required(AllowEmptyStrings = false)]
    [DataType(DataType.DateTime)]        
    public Nullable<System.DateTime> dte_createdon { get; set; }

    [StringLength(10)]        
    public string equip_mode { get; set; } 
}

我可以使用上面的类来验证客户端应用程序发送给API的数据但是如何才能将模型和验证发送给客户端?

1 个答案:

答案 0 :(得分:0)

您可以将Model 400 BadRequest与ModelState一起返回。

    [Authorize(Roles = "Admin, Secretary")]
    [HttpPost]
    [ActionName("Create")]
    public IHttpActionResult PostCreate(SalesOrderRequestModel request)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }            

        return Ok();
    }

这将使API返回如下响应:

{"Message":"The request is invalid.","ModelState":{"model.Email":["Email is required."],"model.FirstName"
:["First name must be 2-30 characters in length.","First name is required."],"model.LastName":["Last
 name must be 2-30 characters in length.","Last name is required."],"model.CountryCode":["Country is
 required."],"model.Address1":["Address must be 5-150 characters in length.","Address is required."]
,"model.Role":["Role is required."]}}

如果您使用的是JavaScript,则会使用ModelState错误填充数组。

function getModelState(data) {

    var errors = [];
    if (data != undefined) {
        for (var key in data.ModelState) {
            for (var i = 0; i < data.ModelState[key].length; i++) {
                errors.push(data.ModelState[key][i]);
            }
        }
    }

    return errors;

};

您现在可以将API的整个响应传递给此函数,它将返回一个包含所有验证错误的字符串数组。