[C#][WebApi] How to create a C# Console Application and configure Owin to host WebApi

seung-jae hwang·2019년 3월 27일
0

CSharpUP

목록 보기
2/3

From : https://medium.com/@Rocco_Sen/how-to-create-a-c-console-application-and-configure-owin-to-host-webapi-3f3e772666cf

  1. Create the Startup.cs class for OWIN configuration. Create this in the root of your project.
    using Microsoft.Owin;
    using Owin;
    using System.Web.Http;
    [assembly: OwinStartup(typeof(OwinAPI.Startup))]
    namespace OwinAPI
    {
    public class Startup
    {
    public void Configuration(IAppBuilder app)
    {
    // Configure Web API for self-host.
    // Note: I prefer my routes to be "api/{controller}/{action}" instead of "api/{controller}/{id}"
    HttpConfiguration config = new HttpConfiguration();
    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}",
    defaults: new { id = RouteParameter.Optional }
    );
    app.UseWebApi(config);
    }
    }
    }
  2. Edit static void main to host OWIN.
    Note: I’m using http://localhost:9000. Use whatever URL you would like OWIN to host.

using Microsoft.Owin.Hosting;
using System;
namespace OwinAPI
{
class Program
{
const string url = "http://localhost:9000";
static void Main(string[] args)
{
using (WebApp.Start(url))
{
Console.WriteLine("Server started at:" + url);
Console.ReadLine();
}
}
}
}
5. Add an API controller.
I like to group my controllers together in a folder called “Controller”. Here is the code for the ApiController. It just returns an array of words.

using System.Collections.Generic;
using System.Web.Http;
namespace OwinAPI.Controller
{
public class TestController : ApiController
{
public IEnumerable GetTest()
{
return new string[] { "One", "Two", "Three" };
}
}
}
6. Test (Make a request to URL see if everything works.)
localhost:9000/api/test/gettest
Testing out the API

0개의 댓글