OWIN Middleware開發入門

風靈使發表於2018-07-24

Program.cs

using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using System;

namespace OWINDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var baseAddress = "http://localhost:9001";
            WebApp.Start<Startup>(url: baseAddress);
            Console.WriteLine("exit by any key");
            Console.ReadLine();
        }
    }
}

Startup.cs

using Owin;
using System.Web.Http;

namespace OWINDemo
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute(
                name:"DefaultApi",
                routeTemplate:"api/{controller}/{id}",
                defaults:new {id=RouteParameter.Optional}
                );
            appBuilder.UseWebApi(config);
            appBuilder.Use<SampleMiddleware>("[自定義可選的object引數]");
        }
    }
}

BlogController.cs

using System.Collections.Generic;
using System.Web.Http;

namespace OWINDemo
{
    public class BlogController: ApiController
    {
        string[] app=new string[] { "南通", "開發區"};
        public IEnumerable<string> Get()
        {
            return app;
        }
        public string Get(int id)
        {
            return $"owin {app[id]} by:wu";
        }
        public void Post([FromBody]string value)
        {
            app[0] = "valuePost";
        }
        public void Put(int id,[FromBody]string value)
        {
            app[id] = "Put";
        }
        public void Delete(int id)
        {
            app[id] = "null";
        }
    }
}

SampleMiddleware.cs

using System;
using System.Threading.Tasks;
using Microsoft.Owin;

namespace OWINDemo
{
    public class SampleMiddleware:OwinMiddleware
    {
        private object _mOptions;


        /// <summary>
        /// 建構函式,第一個引數必須為 OwinMiddleware物件 ;第一個引數是固定的,後邊還可以新增自定義的其它引數
        /// </summary>
        /// <param name="next">下一個中介軟體</param>
        public SampleMiddleware(OwinMiddleware next,object options) 
            : base(next)
        {
            _mOptions = options;
        }


        /// <summary>
        /// 處理使用者請求的具體方法,該方法是必須的
        /// </summary>
        /// <param name="context">OwinContext物件</param>
        /// <returns></returns>
        public override Task Invoke(IOwinContext context)
        {
            PathString tickPath = new PathString("/tick");
            //判斷Request路徑為/tick開頭
            if (context.Request.Path.StartsWithSegments(tickPath))
            {
                string content = DateTime.Now.Ticks.ToString();
                //輸出答案--當前的Tick數字
                context.Response.ContentType = "text/plain";
                context.Response.ContentLength = content.Length;
                context.Response.StatusCode = 200;
                context.Response.Expires = DateTimeOffset.Now;
                context.Response.Write(content);
                //解答者告訴Server解答已經完畢,後續Middleware不需要處理
                return Task.FromResult(0);
            }
            else
                //中介軟體的實現程式碼
                return Next.Invoke(context);
        }
    }
}

執行結果如圖:

這裡寫圖片描述

這裡寫圖片描述

這裡寫圖片描述

相關文章