1
votes

I'm migrating from Java to ASP.NET and I'm trying to implement a WebAPI with OWIN OAuth token security.

I'm getting stuck on this error:

Error 1 'System.Net.Http.Formatting.MediaTypeFormatterCollection' does not contain a definition for 'OfType' and no extension method 'OfType' accepting a first argument of type 'System.Net.Http.Formatting.MediaTypeFormatterCollection' could be found (are you missing a using directive or an assembly reference?)

Here is my Startup class, in which I'm getting the error.

using WebApi.Controller;
using Newtonsoft.Json.Serialization;
using Owin;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace WebApi
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration httpConfig = new HttpConfiguration();
            ConfigureOAuthTokenGeneration(app);
            ConfigureWebApi(httpConfig);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            app.UseWebApi(httpConfig);
        }

        private void ConfigureOAuthTokenGeneration(IAppBuilder app)
        {
            app.CreatePerOwinContext(DbContext.Create);
            app.CreatePerOwinContext<UsuarioManager>(UsuarioManager.Create);
        }

        private void ConfigureWebApi(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            //This line is with the error in the topic
            var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
    }
}
1

1 Answers

3
votes

You're likely missing a reference to

using System.Linq;

At least for me, that's the only difference between my startup and yours, and mine compiles and runs correctly. Annoyingly you can't auto-resolve this error so it's difficult to tell what's missing. I usually don't bother running "Remove Unused Usings" since this kind of error commonly occurs when I later realize I need some new code in a class.

If it's not that, then double check all your nuget packages and .Net version.