How to get actionresult statuscode in asp net core

Introduction

ASP.NET is a popular programming language used for web applications. One common requirement in web development is to retrieve the status code of an ActionResult in ASP.NET Core. In this article, we will explore different ways to achieve this.

Using the StatusCode property

The simplest way to get the status code of an ActionResult is by accessing the StatusCode property. This property is available on the ActionResult object and returns an integer the HTTP status code.


public IActionResult MyAction()
{
    // Perform some logic

    return StatusCode(200);
}

In the above example, we have a action called MyAction that returns a status code of 200. To retrieve this status code, we can the StatusCode property of the returned ActionResult object.


public IActionResult AnotherAction()
{
    // Perform some logic

    var result = StatusCode(404);

    // Access the status code
    var statusCode = result.StatusCode;

    // Do  with the status code

    return result;
}

In the above example, we assign the StatusCode(404) to a variable called result. We can then access the StatusCode property of the result object to retrieve the status code.

Using the HttpContext

Another way to get the status code of an ActionResult is by using the HttpContext object. The HttpContext provides access to various and to the current HTTP request and response.


public IActionResult MyAction()
{
    // Perform some logic

    HttpContext.Response.StatusCode = 200;

    // Do something with the status code

    return View();
}

In the above example, we set the status code directly on the HttpContext.Response object. We can then access this status code from anywhere within the current request context.

Conclusion

the status code of an ActionResult in ASP.NET Core can be done using the StatusCode property of the ActionResult object or by accessing the HttpContext.Response.StatusCode property. Both methods provide a straightforward way to retrieve the status code and perform any necessary actions based on it.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents