c# - 如何在变量 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 以执行操作。
解决方案
我们通常使用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
在这里看到更多。
推荐阅读
- android - 光标越过 Xamarin.Forms 中的线时的分割线效果
- vue.js - Vue PublicPath 在某些情况下没有获取根 url
- python - 将列表拆分为嵌套列表
- kubernetes - EKS - Pod 在 t2.large 实例(t2.large,Bottlerocket OS)上有未绑定的即时 PersistentVolumeClaims
- kubernetes - 在 GKE 中将 Postgres 安装为 NFS,并部署了多个微服务
- laravel - 如何将数据从 Laravel 会话文件默认迁移到 Redis
- mongodb - 将用户从 MongoDB 转移到 firebase
- ruby - 如何确定已安装的 ruby 版本?
- python - 每次我这样做时,如何使用 Selenium 从 instagram 获取帖子 url,每次我向下滚动时它都会动态变化?
- python - 如何检查鼠标和矩形对象之间的碰撞