我正在创建一个新的webapi模式,我决定使用一个新模式来保持一致性.
我正在尝试在我的类对象的构造函数上设置我的错误消息 Pessoa
public class PessoaModel
{
public int PessoaId { get; set; }
public string PessoaNome { get; set; }
public string PessoaNomeFantasia { get; set; }
public string PessoaCnpjCpf { get; set; }
public string PessoaEmail { get; set; }
PessoaModel()
{
if (PessoaNome == null)
throw new Exception("Preencha Nome");
if (PessoaEmail == null)
throw new Exception("Preencha Email");
if (PessoaCnpjCpf == null)
throw new Exception("Preencha Cpf ou Cnpj");
}
}
Run Code Online (Sandbox Code Playgroud)
然后发生异常,但控制器继续运行
[HttpPost]
[Route("Pessoa")]
public IHttpActionResult Post(PessoaModel pessoa)
{
if (_pessoa.Insert(pessoa))
return Ok();
return BadRequest("Pessoa não inserida");
}
Run Code Online (Sandbox Code Playgroud)
有人知道这项工作是怎么做的,或者有更好的方法来做到这一点?
你在做什么没有意义.您正在强制属性具有值,您没有为其赋值.那时,它们只能从构造函数中设置.
由于您使用的是MVC/Web API,我会考虑使用数据注释来强制模型具有正确的值.
public class PessoaModel
{
[Required(ErrorMessage = "ID is required.")]
public int PessoaId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在你的行动中:
if (!this.ModelState.IsValid)
{
return RedirectToAction("Error"); // give an error, do something else
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |