How to return a specific status code and no contents from Controller?

前端 未结 5 1009
谎友^
谎友^ 2020-11-28 02:29

I want the example controller below to return a status code 418 with no contents. Setting the status code is easy enough but then it seems like there is something that needs

5条回答
  •  无人及你
    2020-11-28 03:18

    Look at how the current Object Results are created. Here is the BadRequestObjectResult. Just an extension of the ObjectResult with a value and StatusCode.

    https://github.com/aspnet/Mvc/blob/master/src/Microsoft.AspNetCore.Mvc.Core/BadRequestObjectResult.cs

    I created a TimeoutExceptionObjectResult just the same way for 408.

    /// 
    /// An  that when executed will produce a Request Timeout (408) response.
    /// 
    [DefaultStatusCode(DefaultStatusCode)]
    public class TimeoutExceptionObjectResult : ObjectResult
    {
        private const int DefaultStatusCode = StatusCodes.Status408RequestTimeout;
    
        /// 
        /// Creates a new  instance.
        /// 
        /// Contains the errors to be returned to the client.
        public TimeoutExceptionObjectResult(object error)
            : base(error)
        {
            StatusCode = DefaultStatusCode;
        }
    }
    

    Client:

    if (ex is TimeoutException)
    {
        return new TimeoutExceptionObjectResult("The request timed out.");
    }
    

提交回复
热议问题