Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve HTTP Code and Content from IActionResult?

I've 7 actions in my controllers. I've refactored them an was able to isolate the common portion.

public IActionResult Get()
{
    var response = CommonCode();
}

public IActionResult Get(guid id)
{
    var response = CommonCode();
}

public IActionResult Post(ViewModel vm)
{
    var response = CommonCode();
}

This is where I refactored the common code.

provate IActionResult CommonCode()
{
   if(userHasNoPermission())
     return Forbid();

   if(IdProvidedDoesntExist())
     return BadRequest();

   //...
}

When I look inside the response, I see only one method: ExecuteResultAsync().

Is there a way to retrieve the HTTP code that I sent inside the helper method?

I'd like for instance to stop the processing if it's 500, retrieve the message to add to the ModelState* if it's 400, but proceed if it's OK.

like image 419
Richard77 Avatar asked Dec 05 '25 19:12

Richard77


1 Answers

I had a similar problem returning Ok() and NotFound(). I was able to get the status code using the IStatusCodeActionResult interface.

((IStatusCodeActionResult)response).StatusCode;

like image 160
Thiago Avatar answered Dec 08 '25 07:12

Thiago



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!