如何同时返回自定义的HTTP状态码和内容?

7
我是一个有用的助手,可以将文本翻译成中文。
我有一个在ASP.NET Core中编写的WebApi控制器,并希望返回自定义HTTP状态代码以及自定义内容。
我知道:
return new HttpStatusCode(myCode)

and

return Content(myContent)

我正在寻找类似于以下的东西:
return Content(myCode, myContent)

或者说,已经有一些内置的机制可以完成这个任务。到目前为止,我找到了这个解决方案:
var contentResult = new Content(myContent);
contentResult.StatusCode = myCode;
return contentResult;

这是另一种推荐的实现方式吗?
4个回答

20

您可以使用 ContentResult

return new ContentResult() { Content = myContent, StatusCode = myCode };

1
谢谢 - 这看起来比我的代码更易读。可能 Content 方法做了更多的事情,比如将内容类型标头设置为纯文本。 - user2916547
2
在 .NET 6.0 中,它看起来像这样:return new ContentResult() { Content = myContent, StatusCode = StatusCodes.Status400BadRequest }; - mfcallahan

3

您需要使用HttpResponseMessage。

以下是样例代码:

// GetEmployee action  
public HttpResponseMessage GetEmployee(int id)  
{  
   Employee emp = EmployeeContext.Employees.Where(e => e.Id == id).FirstOrDefault();  
   if (emp != null)  
   {  
      return Request.CreateResponse<Employee>(HttpStatusCode.OK, emp);  
   }  
   else  
   {  
      return Request.CreateErrorResponse(HttpStatusCode.NotFound, " Employee Not Found");  
   }  

} 

更多信息请点击这里


2

我知道这是一个老问题,但你可以通过使用ObjectResult来处理非字符串响应。

如果无法继承自ControllerBase

return new ObjectResult(myContent)
{
    StatusCode = myCode
};

如果您正在从ControllerBase继承的类中,那么StatusCode是最简单的:

return StatusCode(myCode, myContent);

0

我个人使用StatusCode(int code, object value)来从控制器返回HTTP代码和消息/附件/其他内容。

现在我假设您是在普通的ASP.NET Core控制器中进行此操作,因此我的答案可能完全错误,具体取决于您的用例。

以下是我代码中使用的快速示例(我将注释掉所有非必要的内容):

[HttpPost, Route("register")]
public async Task<IActionResult> Register([FromBody] RegisterModel model)
{
    /* Checking code */

    if (userExists is not null)
    {
        return StatusCode(409, ErrorResponse with { Message = "User already exists." });
    }

    /* Creation Code */

    if (!result.Succeeded)
    {
        return StatusCode(500, ErrorResponse with { Message = $"User creation has failed.", Details = result.Errors });
    }

    // If everything went well...
    return StatusCode(200, SuccessResponse with { Message = "User created successfuly." });
}

如果你问的话,这个例子虽然是用 .NET 5 显示的,但也适用于之前的 ASP.NET 版本。但既然我们谈到了 .NET 5,我想指出 ErrorResponseSuccessResponse 是记录类型,用于标准化我的响应,如下所示:
public record Response
{
    public string Status { get; init; }
    public string Message { get; init; }
    public object Details { get; init; }
}

public static class Responses 
{
    public static Response SuccessResponse  => new() { Status = "Success", Message = "Request carried out successfully." };
    public static Response ErrorResponse    => new() { Status = "Error", Message = "Something went wrong." };
}

现在,正如你所说,你正在使用自定义HTTP代码,使用int作为代码非常完美。 它做到了它所说的,所以这对你来说应该很好用;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接