如何从MVC Web API返回返回模型的错误消息?

时间:2014-04-12 11:44:29

标签: asp.net-mvc http asp.net-web-api model

我有这个方法

[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
}

1 个答案:

答案 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"}