c#如何在 IEnumerable返回自定义 HTTP 状态代码 + 消息功能

发布时间: 2017/2/25 3:54:42
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.
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' 到 '如'。显式转换存在 (是否缺少铸?)

如何解决这个问题??

解决方法 1:

重构行动来回报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
    }
}
官方微信
官方QQ群
31647020