转换为'Task'的异步lambda表达式返回委托不能返回值

时间:2017-09-08 22:48:37

标签: c# asp.net-core async-await

我在ASP.NET核心应用程序中有以下内容(Startup.csConfigure方法):

我刚刚添加了async关键字,因为我需要await一个... 所以现在,我得到以下内容:

  

错误CS8031异步lambda表达式转换为'Task'返回   委托不能返回值。您打算退回“Task<T>”吗?

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ITableRepositories repository)
{
    // ...  
    app.UseStaticFiles();    
    app.UseCookieAuthentication();

    app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
    {
        ClientId = Configuration["..."],
        Authority = Configuration["..."],
        CallbackPath = Configuration["..."],
        Events = new OpenIdConnectEvents
        {
            OnAuthenticationFailed = context => { return Task.FromResult(0); },
            OnRemoteSignOut = context => { return Task.FromResult(0); },
            OnTicketReceived = async context =>
            {
                var user = (ClaimsIdentity)context.Ticket.Principal.Identity;
                if (user.IsAuthenticated)
                {
                    var firstName = user.FindFirst(ClaimTypes.GivenName).Value;
                    // ...
                    List<Connection> myList = new List<Connection>() { c };
                    var results = await repository.InsertOrMergeAsync(myList);
                    var myConnection = (results.First().Result as Connection);                         
                }
                return Task.FromResult(0); // <<< ERROR HERE ....... !!!
            },
            OnTokenValidated = context => { return Task.FromResult(0); },
            OnUserInformationReceived = context => { return Task.FromResult(0); },
        }
    });

    app.UseMvc(routes =>        { ...        });
}

enter image description here

在这种情况下我该返回什么?我尝试return 0;,但错误消息没有改变......

PS。 OnTicketRecieved签名

namespace Microsoft.AspNetCore.Authentication
{
    public class RemoteAuthenticationEvents : IRemoteAuthenticationEvents
    {
        public Func<TicketReceivedContext, Task> OnTicketReceived { get; set; }

1 个答案:

答案 0 :(得分:7)

错误信息实际上是不言自明的:

  

转换为'Task'返回委托的异步lambda表达式无法返回值。您打算返回'Task<T>'吗?

所以你有一个async lambda表达式,它应该为Task返回Task<T>而不是T

但是当你执行return 0时,你返回一个int,所以你的异步方法的返回类型是Task<int>,而不是Task。编译器要求你做的是返回 no value

OnTicketReceived = async context =>
{
    await Task.Delay(100);
    return;
}