Nancy host Host releases web application with Razor view and installs Mono to compile and run under Linux

Preface

One,

CSharp web applications are generally published on the IIS server. It is very troublesome to run C# web applications on Linux.

If an application has too many factors such as the associated class library and the external environment, the more things to do and the more troubles it will encounter when porting it.

NancyFx is an excellent C# library that can publish web servers independently. The official description is as follows:

Nancy is a lightweight, low-ceremony, framework for building HTTP based services on .NET Framework/Core and Mono.


two,

The NancyFx library was released before NetCore, and the support for NetFramewok 3.5 and 4 is better. The latest version of Linux corresponding to the same period is Mono4.

Later Framework4.5+, NETCore, and NET Standard versions have been continuously split, moving towards chaos, and are incompatible with each other. Net5 is said to be a unified, God knows what MS will do.

Just like Apple SwiftCode, the API interface has never been stable and changes with each version.

The same code was compiled under the new Framewok two years later, and it is likely to be scrapped. .

After Microsoft acquired Xamarin, Mono has gradually lost its way since 5.0. . .

The Android library is also a bit confusing now, at least it is still partially compatible with the old API. An SDK Manage solves the problem of code compatibility. There is no need to download this SDK, install the Framework, and have a lot of pre-conditions.

Therefore, the deeper the original library is used, the deeper it will be pitted.

Although third-party libraries are not satisfactory in some respects, at least the API will not change. The code accumulated in the past few years can still be used, and even UOS in the future can also be used. It is very helpful for hardware configuration, software configuration, system operation and maintenance complexity, training newcomers and other cost-saving resources.

 

This text demonstrates how to use Nancy to publish web services under Windows and Linux.

The text description explains the demonstration process in a concise way. If you feel that the relevant concepts and operations are not clear, please search and learn by yourself.

 

[Windows Run]

1. Download the Nancy source code https://github.com/NancyFx/Nancy/releases on Github. Download the 1.x version.

2. After decompression, use VisualStudio to open sln under src (Vs 2010 2013 2015) 

   Compile Nancy, Nancy.Hosting.Self, Nancy.ViewEngines.Razor respectively. Or simply "regenerate the solution".

   (Need net framework 4.0)
   
   Extract the three dlls compiled above from bin/Debug in their respective directories and copy them to the desktop (or other places).

3. VisualStudio closes the Nancy solution. Create a new project to create a TestNancyRazor console project.


   Copy    the three DLLs compiled above: Nancy.dll; Nancy.Hosting.Self.dll; Nancy.ViewEngines.Razor.dll; copy them to the project directory and add references to them.

   
4. Change Program.cs to the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nancy.Hosting.Self;

namespace TestNancyRazor
{
    class Program
    {
        static void Main(string[] args)
        {
            string url = "http://localhost:8888/";
            HostConfiguration configuration = new HostConfiguration();
            configuration.UrlReservations.CreateAutomatically = true;

            using (var nancySelfHost = new NancyHost(configuration, new Uri(url)))
            {
                nancySelfHost.Start();
                Console.WriteLine("NancySelfHost已启动。。");
                try
                {
                    Console.WriteLine("正在启动 " + url);
                    Console.WriteLine("成功启动 " + url);
                }
                catch (Exception)
                {
                }
                
                //Linux下开启这行,注释下面两行
                //while (true)System.Threading.Thread.Sleep(1000);
                
                //Windows下开启这两行,注释上面那一行。
                Console.Read();
                nancySelfHost.Stop();
            }
            Console.WriteLine(url + " 已经停止 \n NancySelfHost已关闭。。");            

        }
    }
}


5. Create a new RoutePath.cs, the code is as follows

namespace Nancy.Demo.Hosting.Self
{
    using System.Linq;

    public class RoutePath : NancyModule
    {
        public RoutePath()
        {
            Get["/{file}.cshtml"] = parameters =>
            {
                return View[(string)parameters.file];
            };

            /*
             * 这样配置就可以模拟MVC,完全绕过了Nancy和Asp内置的MVC!
            Get["/{action}"] = parameters =>
            {
                string action = (string)parameters.action;
                if( action.IndexOf("jn") == 0 )
                {
                    return Response.AsText("Json数据可以写成这样,在cshtml里可以直接写入HTML代码");
                }
                return View[(string)parameters.action];
            }
             */

            
            //更深入的路由,网搜:Nancy 路由
        }
    }
}


/*
Static resource access, web search: StaticContentConventionBuilder.AddDirectory 

conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("statics"));

IRootPathProvider.GetRootPath() { return System.Environment.CurrentDirectory + "/"; }
*/


5. Press F5 to compile. After running successfully, open the browser and locate locahost:8888/ to see the effect page. (curl http://localhost:8888/)

6. Create a directory named Views under TestNancyRazor / bin / Debug /. Create a rz.cshtml file under Views, the code is as follows

<h1>hello</h1>
@System.DateTime.Now.ToString()

    

7. Visit (curl) locahost:8888/rz.cshtml in the browser to see the effect


So far, compiling Nancy and running Razor page successfully under Windows.

Now compile Mono source code to run under Linux.

 

[Linuw Run]
1. Open the Mono website: http://download.mono-project.com/sources/mono/, download the source code and compile it. (CentOS 6.8)

# wget http://download.mono-project.com/sources/mono/mono-4.8.1.0.tar.bz2
# tar jxvf mono-4.8.1.0.tar.bz2
# cd mono-4.8.1.0

# yum -y install gcc gcc-c++ # Need to install gcc
# ./configure --prefix=/usr/local
# make # The process takes 15 to 30 minutes
# make install

2. Download the NancyFx.tar.gz source package


# ## https://github.com/NancyFx/Nancy/releases/
# wget https://codeload.github.com/NancyFx/Nancy/ tar.gz/
# tar -zxvf xxx.tar.gz
# cd Nancy/ src # Enter the Nancy/src directory


### Compile Nancy.dll
# cd Nancy  
# xbuild Nancy.csproj


### 编译 Nancy.Hosting.Self.dll
# cd  Nancy.Hosting.Self
# xbuild   Nancy.Hosting.Self.csproj


### 编译 Nancy.ViewEngines.Razor.dll
# cd Nancy.ViewEngines.Razor
# xbuild Nancy.ViewEngines.Razor.csproj

Build succeeded.
         0 Error(s)
         
Compilation is completed, return to the bash interface, if the above prompt appears, it means the compilation is successful.

(Test environment: VM CentOS 6.9, ali yun repository)


3. Copy the entire TestNancyRazor project created in VisualStudio above to Linux. (No need to copy bin/ and obj/)


Fourth, locate the TestNancyRazor folder name under Linux

Copy the three dlls that were successfully compiled with mono just now: Nancy.dll; Nancy.Hosting.Self.dll; Nancy.ViewEngines.Razor.dll; copy them to the TestNancyRazor folder, overwrite the original dll compiled under win 

### The input command is roughly as follows
# cd TestNancyRazor
# rm *.dll -f
# cp Nancy.Three .dll ./

Modify the code according to the comments in Program.cs.

Then, compile the TestNancyRazor project

# xbuild TestNancyRazor.csproj


Five, after the compilation is successful

# cd bin/Debug

Copy the newly created Views directory and the files in it to this Debug directory.

### Run

### pwd = TestNancyRazor/bin/Debug/
# mono TestNancyRazor.exe # Add & run in the background, use kill command to close.


6. Visit locahost:8888/rz.cshtml to see the effect

# services iptables stop #After disabling iptables, other machines on the LAN can be accessed by typing in IP.


Attached:

Apache reverse proxy

<VirtualHost *:80>
    ProxyPass /nc/ http://localhost:8888/
    ProxyPassReverse /nc/ http://ip:8888/
</VirtualHost>

Nginx reverse proxy

location /nc { 
    proxy_pass http://127.0.0.1:8888; 
}
 

Guess you like

Origin blog.csdn.net/RoadToTheExpert/article/details/108362297