[英]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");
}
}
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 的主题,我想指出
ErrorResponse
和SuccessResponse
是用于标准化我的响应的记录,如下所示:
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.