繁体   English   中英

从 ActionResult 中获取值<object>在 ASP.Net Core API 方法中<div id="text_translate"><p>我尝试从 ASP.NET 核心 API 方法中的ActionResult&lt;object&gt;获取值。</p><p> API 有不同的 controller。 我尝试使用 controller A 中的 controller B 中的方法返回结果值。 我从 controller B 得到一个ActionResult object。我可以在ResultObject中使用调试器查看该值,但是如何访问其中的结果值?</p><pre> public ActionResult&lt;object&gt; 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} &lt;-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 }</pre> <p><img src="https://i.stack.imgur.com/4Lppi.jpg" alt="在此处输入图像描述"></p></div></object>

[英]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 中的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM