[英]Get a Value from ActionResult<object> in a ASP.Net Core API Method
我尝试从 ASP.NET 核心 API 方法中的ActionResult<object>
获取值。
API 有不同的 controller。 我尝试使用 controller A 中的 controller B 中的方法返回结果值。 我从 controller B 得到一个ActionResult
object。我可以在ResultObject
中使用调试器查看该值,但是如何访问其中的结果值?
public ActionResult<object> getSourceRowCounter(string sourcePath) //Method from Controller A
{
var result = ControllerB.GetValue($"{sourcePath}.{rowCounterVariableName}");
var result2 = result.Value; //null
var result3 = result.Result; //typ: {Microsoft.AspNetCore.Mvc.OkObjectResult} <-see Value=4 in it with Debugger
//var result4 = result3.Value; //Error?!
//var result5 = result3.Content; //Error?!
//var result6 = result3.?????; //How can i get the Value = 4?
return Ok(result); //should only return value 4 and not the whole object
}
如果您确定它是OkObjectResult
的一种类型,请在使用它之前进行转换,如下所示:
var result3 = (OkObjectResult)result.Result; // <-- Cast is before using it.
var result4 = result3.Value; //<-- Then you'll get no error here.
如果您从操作中调用 API 并且 API 返回您想要在操作中访问的 Ok(result),那么下面的代码可以帮助您:
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return Ok(response.Content); // returns API result
}
Repository.cs
中有示例 function :public async Task<IEnumerable<Todo>> GetTodosAsync() =>
await _context.Todos.ToListAsync();
Controller.cs
如下所示:public async Task<ActionResult<IEnumerable<Todo>>> GetTodosAsync() =>
Ok(await _repository.GetTodosAsync());
UnitTest.cs
中,您可以通过执行以下操作获得结果:var result = await controller.GetCustomersAsync();
// list of todos is in `actual` variable
var actual = (result.Result as OkObjectResult).Value as IEnumerable<CustomerPayload>;
// or use `ObjectResult` instead of `OkObjectResult` for multiple types
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.