如何在变量 C# 中捕获 IActionResult 方法 return 的状态代码
How to capture the status code of an IActionResult Method return in a variable C#
我有以下方法:
public IActionResult DoSomeThing()
{
try
{
Some code...
}
catch (Exception)
{
return BadRequest();
}
return Ok();
}
我有另一种方法,我必须从中捕获 DomeSomething () 方法 returns 给我的变量:
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 才能执行操作。
我们通常使用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
here。
我有以下方法:
public IActionResult DoSomeThing()
{
try
{
Some code...
}
catch (Exception)
{
return BadRequest();
}
return Ok();
}
我有另一种方法,我必须从中捕获 DomeSomething () 方法 returns 给我的变量:
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 才能执行操作。
我们通常使用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
here。