我有这个方法
[HttpPost]
public ContactModel Contact()
{
// validation contact must have at least first name
if (contactModel.firstName == null)
return null; // This works fine
/*
if (contactModel.firstName == null)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please provide first name"); // it gives error
// insert to database
}
那么,我如何指示用户至少提供名字。我想为回复添加一些标题,但这不是用户友好的。
我还添加了
if (contactModel.firstName == null)
{
Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please provide first name"); // this doesn't do any good either.
return null; // This works fine
}
答案 0 :(得分:1)
CreateErrorResponse
返回HttpResponseMessage
,无法转换为ContactModel
。您想要抛出HttpResponseException
并使用CreateErrorResponse
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,
"Please provide first name"));
这将返回带有以下json的HTTP 400(错误请求):
{"Message":"Please provide first name"}