如何在IEnumerable <xxx.models.xxx>函数中返回自定义HTTP状态代码+消息

时间:2016-12-23 18:12:36

标签: c# asp.net asp.net-web-api http-status-code-404

public IEnumerable<xxx.Models.Product> ReviewAll(string para1, string para2, string para3, int para4)
{
    return //HTTPStatusCode
}

目前我正在使用此

int HTTPResponse=400;
return Request.CreateResponse((HttpStatusCode)HTTPResponse, "InvalidID");

但这会返回错误

  

无法隐式转换类型'System.Net.Http.HttpResponseMessage'   到'System.Collections.Generic.IEnumerable'。一个   存在显式转换(您是否错过了演员?)

如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

重构行动以返回HttpResponseMessage

public HttpResponseMessage ReviewAll(string para1, string para2, string para3, int para4) {
    if(some_condition) {
        //...code removed for brevity

        //if request is invalid then return appropriate status response
        int HTTPResponse = 400;
        var response = Request.CreateResponse((HttpStatusCode)HTTPResponse);
        response.ReasonPhrase = "InvalidID";
        return response;
    } else {
        //If the data is valid I need to return the data segment,
        IEnumerable<xxx.Models.Product> responseBody = //...code removed for brevity
        return Request.CreateResponse(HttpStatusCode.Ok, responseBody);//include data with an HttpStatus.Ok (200) response
    }
}