Nancy Async

環境

Nancy使用async/await需要保證項目是.NET 4.5及以上。

句法

可以將Before / After管道和主路由委託指定爲async。 語法與同步代碼幾乎相同,但有以下更改:

  • 前後掛鉤(Before / After)採用兩個參數,即上下文和消除令牌,而不僅僅是上下文。
  • 路徑定義:委託採用兩個參數,捕獲的參數和消除令牌。

Example

using Nancy;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace CoreNancy.Module
{
    public class RoutesModule : NancyModule
    {
        private List<string> Logs { get; set; } = new List<string>();

        public RoutesModule()
        {
            Before += async (ctx, ct) =>
            {
                this.AddToLog("Before Hook Delay\n");
                await Task.Delay(5000);

                return null;
            };

            After += async (ctx, ct) =>
            {
                this.AddToLog("After Hook Delay\n");
                await Task.Delay(5000);
                this.AddToLog("After Hook Complete\n");

                ctx.Response = this.GetLog();
            };

            Get("/Async/{name?Nancy}", async (x, ct) =>
           {
               this.AddToLog("Par:"+x.name+ "\n");

               this.AddToLog("Delay 1\n");
               await Task.Delay(1000);

               this.AddToLog("Delay 2\n");
               await Task.Delay(1000);

               this.AddToLog("Executing async http client\n");
               var client = new HttpClient();
               var res = await client.GetAsync("http://nancyfx.org");
               var content = await res.Content.ReadAsStringAsync();

               this.AddToLog("Response: " + content.Split('\n')[0] + "\n");

               return this.GetLog();
           });
        }

        private void AddToLog(string v)
        {
            Logs.Add(v);
        }

        private Response GetLog()
        {
            return string.Join("", Logs);
        }
    }
}

來看一下結果:

執行順序:Before —> Get —> After

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章