Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API 2 POST-Request not working on mono

I want to write a REST-Server with WEB API 2 on Linux-machine with mono without IIS or something.

What i have done:

  1. Created a Empty C# Console Application
  2. Added the Nuget-Package: Microsoft.AspNet.WebApi.OwinSelfHost, WebApi.Cors for handling CORS-Request

  3. Then i created a Startup.cs for defining my Config;

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseWebApi(ConfigureWebApi());
        }
    
        private HttpConfiguration ConfigureWebApi()
        {
    
            var config = new HttpConfiguration();
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            //Attribute Routing aktivieren
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
    
                "DefaultApi",
    
                "api/{controller}/{id}",
    
                new { id = RouteParameter.Optional });
    
            return config;
        }
    }
    
  4. Edit my Program.cs to act like a server

        class Program
        {
        static void Main(string[] args)
        {
            string baseUrl = "http://*:5000";
            using (WebApp.Start<Startup>(baseUrl))
            {
                Console.WriteLine("Press Enter to quit.");
                Console.ReadKey();
    
            }
        }
    }
    
  5. In this step i add a Model Class Book

    public class Book
    {
        public String Name { get; set; }
        public String Author { get; set; }
    
        public int Id { get; set; }
    }
    
  6. And finaly the BooksController which should handle the requests:

    public class BooksController : ApiController
    {
        public BooksController()
        {}
    
        public async Task<IHttpActionResult> Get()
        {
            List<Book> list = new List<Book>();
            list.Add(new Book() { Name = "myBook",Author = "John" ,Id=1});
            list.Add(new Book() { Name = "myBook2",Author = "Peter",Id=2 });
            return Ok(list);
        }
    
        public async Task<IHttpActionResult> Post(Book requestData)
        {
            return Created<Book>("api/books/" + requestData.Id, requestData);
        }
    }
    

I started this whole application on a Linux-machine with mono-4.0.2 And test the app with the "postman"-Application to create the different HTTP-Requests.

I've testet the server with a GET-Request to /api/books and it worked!

My problem is when i do a POST-Request i get a "500 Internal Server Error" Response.

My POST-Request look like this enter image description here

The strange thing is that when i run my app on a windows machine on the .NET Framework the POST-Request is working without problem!

I don't understand why its not working on mono! And hope someone knows the answer.

like image 400
rubiktubik Avatar asked Mar 16 '23 07:03

rubiktubik


2 Answers

As you said in your own answer, the problem lies with the CORS implementation in Mono.

If you need CORS, you can use a workaround. This is what I did, adapted from this gist: https://github.com/SEEK-Jobs/whatsupwithmono/issues/6

/// <summary>
/// Work around a bug in mono's implementation of System.Net.Http where calls to HttpRequestMessage.Headers.Host will fail unless we set it explicitly.
/// This should be transparent and cause no side effects.
/// </summary>
private class MonoPatchingDelegatingHandler : DelegatingHandler {
    protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
        request.Headers.Host = request.Headers.GetValues("Host").FirstOrDefault();
        return await base.SendAsync(request, cancellationToken);
    }
}

Then in ConfigureWebApi right before you do the call to config.EnableCors, do this:

if(Type.GetType("Mono.Runtime") != null) {
    config.MessageHandlers.Add(new MonoPatchingDelegatingHandler());
}
config.EnableCors();
like image 168
bobbaluba Avatar answered Mar 17 '23 20:03

bobbaluba


Now i find the answer myself :-)

The Problem lies in the CORS Package that i included in the Startup File!

On Windows it has no issues but on Linux and mono the POST-Request is not working anymore!

When i removed the two Cors Lines it worked on mono too.

like image 33
rubiktubik Avatar answered Mar 17 '23 21:03

rubiktubik