nancy03--整合记录(net core版本)

1.Nancy是一个轻量级的用来创建基于HTTP的服务的框架,该框架的可以运行在.net或者mono上。 Nancy处理和mvc类似的DELETE, GET, HEAD, OPTIONS, POST, PUT,PATCH请求,如果你有mvc开发的经验相信可以快速入门。最重要的一点可以让你的Web应用脱离IIS的束缚。

2.添加包

Nancy
Nancy.Owin -- net framework版本的
Microsoft.AspNetCore.Owin 选择相应版本的

3 异步允许 startup.cs中

  public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc();
            // If using Kestrel:
            services.Configure<KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // If using IIS:
            services.Configure<IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });
        }

4 bootstrapper的实现

修改nancy路径

public class CustomRootPathProvider : IRootPathProvider
    {
        //views/Home/index.html
        public string GetRootPath()
        {
            return System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot");
        }
    }

 

public class MyNancyBootstrapper : DefaultNancyBootstrapper
    {
        //private readonly NancyModule _baseSecurityModule = null;
        //
        //public MyNancyBootstrapper(NancyModule nancyModule)
        //{
        //    _baseSecurityModule = nancyModule;
        //}
        //

        protected override IRootPathProvider RootPathProvider => new CustomRootPathProvider();

        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            //Nancy.Security.Csrf.Enable(pipelines);
        }

     // ioc注入
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register<NancyModule, BaseSecurityModule>(); // container.Register<JsonSerializer, CustomJsonSerializer>(); } public override void Configure(INancyEnvironment environment) { environment.Tracing(enabled: true, displayErrorTraces: true); base.Configure(environment); } }

5 一些帮助类

public class EntityFrameWorke
    {
        static ICache cache = new CacheHelper();
        public static bool IsIPUpToLimit(string ipAddr)
        {
            bool flag = false;
            if (cache.Exists(ipAddr))
            {
                var ipCount = cache.Get<string>(ipAddr).ToInt();
                if (ipCount > 5)
                {
                    flag = true;

                }
                else
                {
                    cache.Add(ipAddr, (ipCount + 1).ToString(), 7200);
                    flag = false;
                }
            }
            else
            {
                cache.Add(ipAddr, "1", 7200);
                flag = false;
            }
            return flag;
        }
    }

    public static class Extension{

        public static int ToInt(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException();
            }
            int intRt;
            if (int.TryParse(str, out intRt))
            {
                return intRt;
            }
            else
            {
                throw new Exception("字符串转换失败!");
            }
        }
    }
 /// <summary>
        /// MD5 encrypt
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetEncryptResult(string data, string key)
         {
             HMACMD5 source = new HMACMD5(Encoding.UTF8.GetBytes(key));
             byte[] buff = source.ComputeHash(Encoding.UTF8.GetBytes(data));
             string result = string.Empty;
             for (int i = 0; i<buff.Length; i++)
             {
                 result += buff[i].ToString("X2"); // hex format
             }
             return result;
         }

6 url参数接收类

public class UrlParaEntity 
    {
        public string Type { get; set; }
        public string PageIndex { get; set; }
        public string PageSize { get; set; }
        public string Sign { get; set; }

        public string encryptKey = "12324334.";

        public bool Validate() {
            return this.Sign == EncryptHelper.GetEncryptResult((Type + PageIndex + PageSize), encryptKey);
        }
    }

7 返回界面控制器

 public class HomeModule : NancyModule
    {
        public HomeModule()
        {
            Get("/home/index", _ =>
            {
                return  View;
            });

            //Get("/{bookId}", _ =>
            //{
            //    return View["index.html", new { BookId = _.bookId }];
            //});

            Get("/{bookId}", _ =>
            {
                return View["index.html", new
                {
                    Books = new List<Book> {
                       new Book("S001", "Math 101"),
                       new Book("T001", "C# Programming")
                   }
                }];
             });

        }

        public class Book
        {
            public Book(string isbn, string bookName)
            {
                ISBN = isbn;
                BookName = bookName;
            }

            public string ISBN { get; set; }

            public string BookName { get; set; }
        }
    }

8 界面

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <table>
        <tr>
            ISBN
        </tr>
        <tr>
            Book Name
        </tr>
        <tbody>
            @Each.Books
            <tr>
                <td>
                    @Current.ISBN
                </td>
                <td>
                    @Current.BookName
                </td>
            </tr>
            @EndEach
        </tbody>
    </table>
</body>
</html>

9----Nancy拦截module

public class BaseSecurityModule : NancyModule
    {
        //匿名函数也需要加上
        public BaseSecurityModule()
        {
        }

        public BaseSecurityModule(string baseUrl) : base(baseUrl)
        {
            //写法一
            Before += TokenValidBefore;

            After += xtx => {
                System.Diagnostics.Debug.WriteLine("BaseModule---After");
            };

            OnError += (ctx, ex) => {
                System.Diagnostics.Debug.WriteLine("BaseModule---OnError");
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                return  Response.AsJson(new { data=HttpStatusCode.InternalServerError,message="系统错误,请联系管理员"});
            };
           
          
        }
        private Response TokenValidBefore(NancyContext ctx)
        {
            string ipAddr = ctx.Request.UserHostAddress.Trim();
            if (EntityFrameWorke.IsIPUpToLimit(ipAddr))
            {
                return Response.AsText("up to the limit");
            }

            // 获取请求参数
            //var parameters = ctx.Request.Form();
            var para = this.Bind<UrlParaEntity>();
            return !para.Validate() ? Response.AsText("I think you are a bad man!!") : null;
        }

    }

10 具体api层

public class HomeModule : BaseSecurityModule
    {
        public HomeModule() : base("/api/home/")
        {
            IList<ReturnData> rtlist = new List<ReturnData> {
                new ReturnData() { name="张三",age="1",address="上海",email="1233@qq.com"},
                new ReturnData() { name="李四",age="2",address="苏州",email="832333@qq.com"}
            };

            Get("/product", _ => {
                //var ss = this.BindAndValidate<ReturnData>();
                return Response.AsJson(rtlist); 
            });
        }
    }
    public class ReturnData
    {
        public string name { get; set; }
        public string age { get; set; }
        public string address { get; set; }
        public string email { get; set; }
    }

11缓存类--

posted @ 2021-09-20 22:49  vba是最好的语言  阅读(63)  评论(0编辑  收藏  举报