Nancy 學習-進階部分 繼續跨平台


前面兩篇,講解Nancy的基礎,及Nancy自宿主和視圖引擎。

現在來學習一些進階部分。

 

Bootstrapper

Bootstrapper 就相當於 asp.net 的Global.asax 。

我們自定義Bootstrapper 需要繼承  DefaultNancyBootstrapper

public class CustomBootstrapper : DefaultNancyBootstrapper
{
    protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
    {
         // 你的自定義啟動代碼
    }
}

 我們可以在 ApplicationStartup 中初始化一些參數及方法,也可以在獲取全局異常。

下面我們來看看如何獲取全局異常。

    public class CustomBootstrapper:DefaultNancyBootstrapper
    {
        protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines)
        {
            pipelines.OnError += Error;
        }

        private dynamic Error(NancyContext context, Exception ex) 
        {
            //可以使用log4net記錄異常 ex 這里直接返回異常信息
            return ex.Message;
        }
    }

 

The root path

root path GetRootPath 可以獲取應用根目錄。

我們也可以更改應該根目錄。

更改根目錄需要實現接口 :IRootPathProvider 

首先實現 IRootPathProvider 接口

public class CustomRootPathProvider : IRootPathProvider
{
    public string GetRootPath()
    {
     //程序根目錄 需要絕對路徑
return "C:\\inetpub\\wwwroot"; } }

然后我們在前面的 CustomBootstrapper   override  RootPathProvider

public class CustomBootstrapper : DefaultNancyBootstrapper
{
    protected override IRootPathProvider RootPathProvider
    {
        get { return new CustomRootPathProvider(); }
    }
}

這樣我們就實現了更改應用根目錄。

我們來使用 root path  ,以上傳文件為例。

        public HomeModule(IRootPathProvider path) 
        {

            Post["/file"] = r =>
            {
                var uploadDirectory = Path.Combine(path.GetRootPath(), "uploads");

                if (!Directory.Exists(uploadDirectory))
                {
                    Directory.CreateDirectory(uploadDirectory);
                }

                foreach (var file in Request.Files)
                {
                    var filename = Path.Combine(uploadDirectory, file.Name);
                    using (FileStream fileStream = new FileStream(filename, FileMode.Create))
                    {
                        file.Value.CopyTo(fileStream);
                    }
                }
                return HttpStatusCode.OK;
            };
        }

將文件上傳到根目錄下的 uploads 文件夾。

 

Managing static content

靜態文件管理

現在我們要訪問剛剛上傳的文件,如圖片這些改怎么辦呢。

下面我們來實現這個,Nancy的靜態資源訪問。

我們在前面的 CustomBootstrapper  重寫 ConfigureConventions  方法。

        protected override void ConfigureConventions(NancyConventions conventions)
        {
            base.ConfigureConventions(conventions);
            //添加文件夾 file 請求地址 uploads 是文件夾 也就是物理路徑相對的
            conventions.StaticContentsConventions.AddDirectory("file","uploads");
            //添加文件
            conventions.StaticContentsConventions.AddFile("index.html", "1.html");
        }

 

這樣我們就可以訪問uploads 文件夾的文件了。

 

如果你覺得本文對你有幫助,請點擊“推薦”,謝謝。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM