简体   繁体   English

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

[英]How to return both custom HTTP status code and content?

I have an WebApi Controller written in ASP.NET Core and would like to return a custom HTTP status code along with custom content.我有一个用 ASP.NET Core 编写的 WebApi 控制器,并希望返回自定义 HTTP 状态代码和自定义内容。

I am aware of:我知道:

return new HttpStatusCode(myCode)

and

return Content(myContent)

and I am looking for something along the lines of:我正在寻找以下方面的东西:

return Content(myCode, myContent)

or some in built mechanism that already does that.或一些已经做到这一点的内置机制。 So far I have found this solution:到目前为止,我已经找到了这个解决方案:

var contentResult = new Content(myContent);
contentResult.StatusCode = myCode;
return contentResult;

is another recommended way of achieving this?是实现这一目标的另一种推荐方法吗?

您可以使用ContentResult

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

You need to use HttpResponseMessage您需要使用 HttpResponseMessage

Below is a sample code下面是一个示例代码

// 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");  
   }  

} 

More info here更多信息在这里

I personally use StatusCode(int code, object value) to return a HTTP Code and Message/Attachment/else from a Controller.我个人使用StatusCode(int code, object value)从控制器返回 HTTP 代码和消息/附件/其他。 Now here i'm assuming that you're doing this in a plain normal ASP.NET Core Controller, so my answer may be completely wrong depending on your use case.现在,我假设您在普通的 ASP.NET Core 控制器中执行此操作,因此根据您的用例,我的回答可能完全错误。

A quick example of use in my code (i'll comment out all the non-necessary stuff) :在我的代码中使用的一个快速示例(我将注释掉所有不必要的东西):

[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." });
}

If you were to ask, this example, while shown with .NET 5, works well with previous ASP.NET versions.如果您要问,这个示例虽然与 .NET 5 一起显示,但适用于以前的 ASP.NET 版本。 But since we're on the subject of .NET 5, i'd like to point out that ErrorResponse and SuccessResponse are records used to standardize my responses, as seen here :但由于我们是关于 .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." };
}

Now, as you said you're using Custom HTTP Codes, using int for codes is plain perfect.现在,正如您所说,您使用的是自定义 HTTP 代码,对代码使用int是非常完美的。 It does what it says on the tin, so this should work nicely for you ;)它做它在罐头上说的那样,所以这对你来说应该很好用;)

I know it's an old question but you can do this for non-string responses by using ObjectResult .我知道这是一个老问题,但您可以使用ObjectResult对非字符串响应执行此操作。

If you can't inherit from ControllerBase :如果您不能从ControllerBase继承:

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

If you are in a class inheriting from ControllerBase then StatusCode is the simplest:如果您在从ControllerBase继承的类中,那么StatusCode是最简单的:

return StatusCode(myCode, myContent);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何返回自定义 http 状态码 CoreWCF? - How to return custom http status code CoreWCF? 如何返回 http 错误状态代码以及 class 中的自定义消息 - How to return http error status code along with custom message in a class 如何为SOAP错误返回自定义的http状态代码 - How to return a custom http status code for SOAP faults 从WebAPI返回自定义HTTP状态代码? - Return Custom HTTP Status Code from WebAPI? .NET Core Web API:使用内容类型application / problem + json返回自定义HTTP状态代码 - .NET Core Web API: return a custom HTTP status code with Content Type application/problem+json 如何在ServiceStack中返回不同的Http状态码 - How to return different Http Status Code in ServiceStack 如果找不到要处理的内容,则返回http状态代码200或204 - Return http-status-code 200 or 204 if no content found to process 如何在自定义HandleErrorAttribute中获取http状态代码 - How to get the http status code in custom HandleErrorAttribute 如何使用 HttpWebResponse 处理自定义 HTTP 状态码 - How to handle custom HTTP status code with HttpWebResponse 从WebAPI 2端点返回自定义HTTP状态代码 - Return Custom HTTP Status Code from WebAPI 2 endpoint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM