Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type or namespace name 'Func<,>' could not be found (are you missing a using directive or an assembly reference?

Below is the sample I found from online Tutorial to host the website suing OWIN, however when I try to run on my machine, I got this error

CS0246 The type or namespace name 'Func<,>' could not be found (are you missing a using directive or an assembly reference?)

I think for using 'Func<,>' I have using System, and for IDictionary, I have using System.Collections.Generic; so I don't understand why it still can't work.

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using AppFunc = Func<IDictionary<string, object>, Task>;


public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var middleware = new Func<AppFunc, AppFunc>(MyMiddleWare);

        app.Use(middleware);
        app.Use<OtherMiddleware>();
    }

    public AppFunc MyMiddleWare(AppFunc next)
    {
        AppFunc appFunc = async (IDictionary<string, object> environment) =>
        {
            var response = environment["owin.ResponseBody"] as Stream;
            byte[] str = Encoding.UTF8.GetBytes("My First Middleware");
            await response.WriteAsync(str, 0, str.Length);

            await next.Invoke(environment);
        };
        return appFunc;
    }

    public class OtherMiddleware : OwinMiddleware
    {
        public OtherMiddleware(OwinMiddleware next) : base(next) { }

        public override async Task Invoke(IOwinContext context)
        {
            byte[] str = Encoding.UTF8.GetBytes(" Other middleware");
            context.Response.Body.Write(str, 0, str.Length);

            await this.Next.Invoke(context);
        }
    }
}
like image 647
ckky1213 Avatar asked Nov 04 '25 14:11

ckky1213


2 Answers

You need to put the AppFunc in the class so it can use the using, Or you can use full namespace for Func, IDictionary and Task

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

// Use this
using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;


public class Startup
{
    // Or this
    using AppFunc = Func<IDictionary<string, object>, Task>;

    ...
}
like image 87
Kahbazi Avatar answered Nov 06 '25 03:11

Kahbazi


For me it was low .NET Target Framework version 2.0 of application. Changed to 4.7 (it seems minimal is 3.5).

like image 34
user2091150 Avatar answered Nov 06 '25 04:11

user2091150