【问题标题】:How to return Custom HTTP Status code + message in IEnumerable<xxx.Models.xxx> function如何在 IEnumerable<xxx.Models.xxx> 函数中返回自定义 HTTP 状态代码 + 消息
【发布时间】:2017-05-09 10:21:59
【问题描述】:
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”。一个 存在显式转换(您是否缺少演员表?)

如何解决这个问题??

【问题讨论】:

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


    【解决方案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
        }
    }
    

    【讨论】:

    • No Nkosi。我无法重构操作以返回 HttpResponseMessage,因为我在函数中使用“产品”模型。没有其他办法解决这个问题吗?
    • 你在函数中使用什么并不重要。框架将从响应主体中获取模型并将其返回给调用者,这就是我在 else 语句中所做的。这样您就可以灵活地在响应中返回正确的状态代码。
    • 这个函数不仅返回HTTP响应,还返回数据。如果条件为真,则需要返回基于 xxx.Models.Product 类型的数据,如果条件为假,则返回 HTTP 响应。 :-)
    • 我根据提供的信息给了你解决方案,但你指出它不正确。
    • 你想多了。数据将在响应正文中返回。仔细看答案。事实上,我认为您需要重新阅读有关动作和控制器的内容,以便您可以理解我之前向您解释过的内容。我现在无能为力了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    相关资源
    最近更新 更多