Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the status code with custom message in asp.net core 2.1?

I am working on asp.net core version 2.1, I have created a sample API project which works fine but I am unable to modify the status code with a custom message for example:

In Postman:

200 OK

Expecting:

200 Custom_Message

The code that I tried:

[HttpGet]
public IActionResult Get()
{
     Response.StatusCode = 200;
     Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "Custom_Message";
     return Ok();
}

Postman's current Output:

enter image description here

GitHub Repository

like image 921
Prashant Pimpale Avatar asked Nov 17 '22 11:11

Prashant Pimpale


1 Answers

I think you should create your custom class:

public class CustomResult : OkResult
{
    private readonly string Reason;

    public CustomResult(string reason) : base()
    {
        Reason = reason;
    }

    public override void ExecuteResult(ActionContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = Reason;
        context.HttpContext.Response.StatusCode = StatusCode;
    }
}

Then in your controller method:

[HttpGet]
public IActionResult Get()
{
     return new CustomResult("Custom reason phrase");
}

Output

enter image description here

like image 131
ALFA Avatar answered Dec 27 '22 05:12

ALFA