相关疑难解决方法(0)

ActionResult <IEnumerable <T >>必须返回List <T>

使用ASP.NET Core 2.1获取以下代码:

[HttpGet("/unresolved")]
public async Task<ActionResult<IEnumerable<UnresolvedIdentity>>> GetUnresolvedIdentities()
{
   var results = await _identities.GetUnresolvedIdentities().ConfigureAwait(false);
   return results.ToList();
}
Run Code Online (Sandbox Code Playgroud)

因为我本来以为GetUnresolvedIdentities()回报IEnumerable<UnresolvedIdentity>,我可以只返回

return await _identities.GetUnresolvedIdentities().ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)

除了我不能,因为我得到这个错误:

CS0029无法将类型隐式转换 'System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>''Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.IEnumerable<Data.Infrastructure.Models.UnresolvedIdentity>>'

我需要它.ToList(),这很烦人,因为它是2行而不是1行.

为什么无法ActionResult<T>弄清楚GetUnresolvedIdentities()返回IEnumerable<>并返回那个?

签名GetUnresolvedIdentities是:

Task<IEnumerable<UnresolvedIdentity>> GetUnresolvedIdentities();
Run Code Online (Sandbox Code Playgroud)

c# actionresult asp.net-core asp.net-core-2.1

14
推荐指数
2
解决办法
5485
查看次数

ASP.NET Core 如何将任何类型转换为 ActionResult&lt;T&gt; 返回类型的控制器操作?

我在 ASP.NET Core 2.2 中的 WebApi 控制器中有一个简单的操作,如下所示:

[HttpGet("test123")]
public ActionResult<string> Test123()
{
    return new OkResult();
}
Run Code Online (Sandbox Code Playgroud)

这编译得很好,但我想知道如何将OkResult对象转换为ActionResult<string>

这些类有不同的继承链: OkResult -> StatusCodeResult -> ActionResult while ActionResult<TValue>only implementsIConvertToActionResult 换句话说,ActionResult<string>不是OkResult类的基类型。

如果我手动执行此操作并将代码更改为:

[HttpGet("test123")]
public ActionResult<string> Test123()
{
    var a = new OkResult();
    var b = a as ActionResult<string>;  // Error CS0039

    return b;
}
Run Code Online (Sandbox Code Playgroud)

代码不会编译转换错误:

错误 CS0039:无法通过引用转换、装箱转换、拆箱转换、包装转换或空类型转换将类型“Microsoft.AspNetCore.Mvc.OkResult”转换为“Microsoft.AspNetCore.Mvc.ActionResult”

第一个代码如何工作而第二个代码不起作用?如何从没有公共基类型的对象转换返回类型?

c# asp.net-core

5
推荐指数
1
解决办法
2900
查看次数

标签 统计

asp.net-core ×2

c# ×2

actionresult ×1

asp.net-core-2.1 ×1