Tips and tricks
Dot.NET C# - Mock Custom Http Status Code response in IActionResult
Write this class
public class CustomErrorResult : ActionResult
{
private readonly string _message;
private readonly int _statusCode;
public CustomErrorResult(string message, int statusCode)
{
_message = message;
_statusCode = statusCode;
}
public override void ExecuteResult(ActionContext context)
{
var response = context.HttpContext.Response;
response.StatusCode = _statusCode;
response.ContentType = "application/json";
var result = JsonSerializer.Serialize(new { error = _message });
response.WriteAsync(result);
}
}
Then you can use it like so:
return new CustomErrorResult("Version number is missing", 427);