aspnet / AspNetKatana

Microsoft's OWIN implementation, the Katana project
Apache License 2.0
959 stars 331 forks source link

Always a object reference error when trying to host a webapi in owin self hosted #519

Closed Sicos1977 closed 5 months ago

Sicos1977 commented 5 months ago

I've made a .netstandard 2.0 class library with in it a web api controller

public class SchedulerController : ApiController

There is also a class called StartUp in it with this code

public class Startup
{
    IScheduler _scheduler;

    public void Configuration(IAppBuilder appBuilder)
    {
        var httpConfiguration = new HttpConfiguration();
        httpConfiguration.Formatters.Clear();
        httpConfiguration.Formatters.Add(new JsonMediaTypeFormatter());

        var jsonFormatter = new JsonMediaTypeFormatter();
        httpConfiguration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

        httpConfiguration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "scheduler/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        httpConfiguration.MapHttpAttributeRoutes();

        appBuilder.UseWebApi(httpConfiguration);
        appBuilder.UseStageMarker(PipelineStage.MapHandler);
    }
}

public class JsonContentNegotiator(MediaTypeFormatter formatter) : IContentNegotiator
{
    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)  
    {  
        var result = new ContentNegotiationResult(formatter, new MediaTypeHeaderValue("application/json"));  
        return result;  
    }  
}  

I installed the following packages

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.3.0" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
  </ItemGroup>

I also have a .net6.0 console app in my solution where I call the StartUp class like this

var baseAddress = "http://localhost:44344/";
using var app = WebApp.Start<Startup>(baseAddress);
Console.WriteLine($"Server running at {baseAddress}");
Console.ReadLine();

This al seems to work fine but as soon as I try to send a request from Postman like this

image

I always get this exception... it is driving me nuts... why do I get this?

image

Tratcher commented 5 months ago

These libraries are not supported on .NET 5+, only .NET Framework 4.x. The framework's HttpListener implementation is different and that's causing this error.

On .NET 5+ you should move to AspNetCore instead.

Sicos1977 commented 5 months ago

Any way to solve this so that I can have a .netstandard2.0 that can support both worlds?

Tratcher commented 5 months ago

The only version of Asp.Net that directly supports .netstandard2.0 is AspNetCore 2.1, designed to run on both .NET Framework 4.x and .NET Core 2.1. However, .NET Core 2.1 is out of support.