[英]Get a Value from ActionResult<object> in a ASP.Net Core API Method
I try to get a value from ActionResult<object>
in an ASP.NET Core API method.我尝试从 ASP.NET 核心 API 方法中的
ActionResult<object>
获取值。
The API has a different controller. API 有不同的 controller。 I try to use a method from controller B in controller A to return the result value.
我尝试使用 controller A 中的 controller B 中的方法返回结果值。 I get an
ActionResult
object from controller B. I can see the value with the debugger in the ResultObject
but how can I get access to the result value in it?我从 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
}
If you're sure that it is a type of OkObjectResult
then cast before using it like below:如果您确定它是
OkObjectResult
的一种类型,请在使用它之前进行转换,如下所示:
var result3 = (OkObjectResult)result.Result; // <-- Cast is before using it.
var result4 = result3.Value; //<-- Then you'll get no error here.
If you are calling an API from action and the API returns Ok(result) which you want to access in your action then below code can help you:如果您从操作中调用 API 并且 API 返回您想要在操作中访问的 Ok(result),那么下面的代码可以帮助您:
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
return Ok(response.Content); // returns API result
}
Repository.cs
:Repository.cs
中有示例 function :public async Task<IEnumerable<Todo>> GetTodosAsync() =>
await _context.Todos.ToListAsync();
Controller.cs
looks like below: Controller.cs
如下所示:public async Task<ActionResult<IEnumerable<Todo>>> GetTodosAsync() =>
Ok(await _repository.GetTodosAsync());
UnitTest.cs
you can get results by doing this: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.