3

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);
        }
    }
}
ckky1213
  • 321
  • 5
  • 14

3 Answers3

4

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>;

    ...
}
Kahbazi
  • 14,331
  • 3
  • 45
  • 76
1

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

user2091150
  • 978
  • 12
  • 25
  • Yup. That was the issue for me too. I was loading up someone else's project, and the framework version was 2.0 as well. – Scott Smith May 25 '20 at 04:03
0

You need to make sure you added the reference System.Runtime.CompileServices to your project as you see in here: https://msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx the delegate is part of mscorlib assembly.