首页 > 解决方案 > 如何在变量 C# 中捕获 IActionResult 方法返回的状态代码

问题描述

我有以下方法:

public IActionResult DoSomeThing()
    {
        try
        {
            Some code...
        }

        catch (Exception)
        {
            return BadRequest();
        }

        return Ok();
    }

我有另一种方法,我必须从中捕获 DomeSomething () 方法在变量中返回给我的内容:

public void OtherMethod()
    {
        var result = DoSomeThing();

        if (result == Here I need to compare with the result, for example if it is a 200 result or Ok, do the action)
        {
            Do an action... 
        }
    }

我需要提取状态代码,例如 result == 200 以执行操作。

标签: c#asp.net-core-mvchttp-status-codes

解决方案


我们通常使用HttpClient来执行这样的操作。你可以在下面看到我的例子。

在你的Startup,添加

services.AddHttpClient();

在您的控制器中:

private readonly IHttpClientFactory _clientFactory;
   
public HomeController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
public IActionResult DoSomeThing()
    {

        return Ok();
    }
public void OtherMethod()
    {
        var URL = "https://localhost:xxxx/home/DoSomeThing";
        var message = new HttpRequestMessage(HttpMethod.Get, URL);
        var client = _clientFactory.CreateClient();
        var response = client.Send(message);
        if (response.IsSuccessStatusCode)
        {
        //...
        }
        else
        {
        }

   }

测试结果: 在此处输入图像描述

你可以HttpClient 在这里看到更多。


推荐阅读