Lightweight MVC framework: Nancy Learning

Source: Internet
Author: User

    • First, know Nancy

Listening to the training on Nancy's framework today was attracted by Nancy's ease of use. So the evening came back to comb a bit of knowledge.

What is Nancy? As stated in the title, Nancy is a lightweight, stand-alone framework:

Nancy is a lightweight for building HTTP-based WEB services based on the. NET and Mono platforms.

Nancy is designed to handle,,,, DELETE GET HEAD OPTIONS POST PUT 和 PATCH etc. request methods and provide a simple and elegant DSL to return the response.

Nancy and ASP. NET MVC are similar in principle but have their own set of routing mechanisms that are more user-friendly and can be used to quickly develop some websites with Nancy. Nancy official website

    • Ii. references to Nancy

  First, create a new ASP. NET Web application:

    

After you've built the project, click "References", right-click on "Manage NuGet Toolkit" and install the Nancy related file as follows:

    

This is the three main files installed during web development, where Viewengines.razor is related to the Razor view in ASP.

After the reference has been added, it is found that the following configuration is generated in Web. config:

    

As can be seen from the configuration file, Nancy defines her own httphandlers class, and all requests are delivered to the Nancy framework for processing. Nancy's configuration is now complete. Let's start with the Hello World tour.

    • Iii. Commencement of a project

After Nancy is configured, the first application begins: "Hello World"

First Nancy also has its own rules, Nancy Project controller parts must be placed in the Modules folder, view parts must be placed in the Views folder,

Add code in Homemodule: Click to run, the effect is as follows:

In ASP. All controllers inherit the controller, and in Nancy, all the ' controllers ' must inherit the Nancymodule class.

Note that in Nancy, all of the routing information is in the construction method, and when the program runs, all of the construction methods are traversed, and if the routing information is the same, the last traversed one is selected by default.

    • Iv. Nancy back and forth interaction (I.)

1.Nancy is how to make a view of the first choice? If you want to display information about the home.cshtml page, Nancy can write:

  
1  Public classHomemodule:nancymodule2     {3          PublicHomemodule ()4         {5get["/"] = P = =6             {7                 returnview[" /Home"];8             };9         }Ten}
View Code

  

2. What if the backend wants to return data to the front end? We can write this:

 Public classHomemodule:nancymodule { PublicHomemodule () {get["/"] = P = ={person Model=NewPerson () {name="Kobe Bryant"}; returnview[" /Home", model];        }; }    }     Public classPerson { Public stringName {Get;Set; } }

This will throw the data to the front end, of course, the front end also need to set up the relevant information to receive the name information, as follows:

  

Using the razor engine, receive the person object data, when displayed, and MVC, as the @model.name can output information, as follows:

  

3.image,file,json etc format data, very convenient. The following is implemented in the code to throw the backend data to the front end:

 public   Homemodule () {get[< /span> " /  "] = P => {person model  = new  person () {Name=  Kobe   " };  return  Response.asjson (new  { result = true , message =  "  Kobe Bryant   });            
//return Response.asxml (model); }; }

  4. In programming, we sometimes need to return different objects, different data to the front-end, what should Nancy do, can meet the existing needs? Here we can use the dynamic type of data. as follows :

 Public classHomemodule:nancymodule {/// <summary>        ///Dynamic type Data/// </summary>        PrivateDynamic model =NULL; protectedDynamic Model {Get            {                if(model = =NULL) {model=NewExpandoObject (); }                returnmodel; }            Set{model=value; }        }        //constructor Function         PublicHomemodule () {get["/"] = P = ={person per=NewPerson () {name="Kobe Bryant"}; Happy Hap=NewHappy () {nba="Basketball" }; Model.person=per; Model.pappy=Hap; returnview[" /Home", model];        }; }    }    //Entity     Public classPerson { Public stringName {Get;Set; } }    //Entity     Public classHappy { Public stringNba {Get;Set; } }

Again, we need to make a declaration on the front-end so that we can refer to it, because the data is dynamic (same as the data type returned by ViewBag), all without smart hints:

  

Note: The dynamic and model.xx are the same as the parameters passed by the backend.

    • V. Nancy back and forth Interaction (II)

The above mainly said the back-end parameters to the front-end, the front-end is how to request it? Here's a description.

1. We often pass a userid to request data, how did Nancy get it, as follows:

such as Url:http://localhost:62412/index?name=james

       //constructor Function         PublicHomemodule () {get["/index"] = P = ={person per=NewPerson (); Per. Name=request.query["Name"];//Get Request Fetch method                returnview[" /Home", per];        }; }

The effect is as follows:

  

2. Request Instance 2, if the requested parameters as part of the URL, how to deal with it? As follows:

  url:http://localhost:62412/index/1

Using {UserId} as a placeholder, P.userid obtains the requested data.

3. What happens if a large amount of request data is processed?

If student information is registered, students need to submit a student number and password, then we can:

First add: Using Nancy.modelbinding;

Second bound entity: Student s = this.  Bind<student> (); To get all the requested information. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingNancy;usingsystem.dynamic;usingnancy.modelbinding;namespacenancystudy.modules{ Public classHomemodule:nancymodule {//constructor Function         PublicHomemodule () {post["/index"] = P = ={Student s= This. Bind<student>(); returnview[" /Home", S];        }; }    }    //Entity     Public classStudent { Public stringName {Get;Set; }  Public stringPWD {Get;Set; } }}

Summary: So far, Nancy's common function has been summed up almost, if interested in continuing to study the Nancy Code. ~~~

Lightweight MVC framework: Nancy Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.