Web API 2 POST-Request does not work on mono

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

What I've done:

  • Created an empty C # console console.
  • Added Nuget package: Microsoft.AspNet.WebApi.OwinSelfHost, WebApi.Cors for processing CORS request

  • Then I created Startup.cs to determine my configuration;

    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;
        }
    }
    
  • Modify my .cs program to act as 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();
    
            }
        }
    }
    
  • At this point I add a model class book

    public class Book
    {
        public String Name { get; set; }
        public String Author { get; set; }
    
        public int Id { get; set; }
    }
    
  • And exit with BooksController, which should handle 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 application with "postman" -Application to create various HTTP requests.

I tested the server using the GET request / api / books and it works!

, POST-, " 500", .

POST- enter image description here

, Windows .NET Framework, POST- !

, ! , - .

+4
2

, CORS Mono.

CORS, . , , : https://github.com/SEEK-Jobs/whatsupwithmono/issues/6

/// <summary>
/// Work around a bug in mono 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);
    }
}

ConfigureWebApi config.EnableCors :

if(Type.GetType("Mono.Runtime") != null) {
    config.MessageHandlers.Add(new MonoPatchingDelegatingHandler());
}
config.EnableCors();
+4

: -)

CORS, !

Windows , Linux POST- !

Cors Lines, .

+3

Source: https://habr.com/ru/post/1599337/


All Articles