Nancy in. NET Core Learning Notes

Source: Internet
Author: User

In the previous article, I introduced the sources and benefits of Nancy and created a simple Nancy app that outputs a "Hello world" in the Web page, and I'll summarize the routes in Nancy

Definition of routes in Nancy

The route in Nancy is defined in the constructor for each module.
In order to create a route, you need to define the following 4 sections

    • Methods for HTTP requests (method)
    • Route template (Pattern)
    • Response Method (Action) to process the corresponding routing template request
    • Conditional constraint (Condition)

The code for the previous article is an example

    public class HelloModule : NancyModule    {        public HelloModule()        {            Get("/", p => "Hello World");        }    }

A route defined in the current construct

    • Its HTTP request method is get
    • Its routing template is "/", that is, the Web site root directory
    • Its response is to output a "Hello world"
    • Here it does not specify any of the conditional constraints
HTTP request method (HTTP method) supported in Nancy

Nancy in Support,,,, DELETE GET HEAD OPTIONS POST , PUT andPATCH

Route template (Pattern) in Nancy

Let's look at some of the routing fragments and constraints that are provided by default in Nancy.

Several route fragments in Nancy

Several route fragments are supported by default in Nancy.

Plain text fragment (Literal Segment)

Example:/products/cocacola

    public class ProductModule : NancyModule    {        public ProductModule()        {            Get("/products/cocacola", p => "Coca Cola");        }    }

Fragment with variable (Capture Segment)

The second parameter of the Get method in Nancy is a Func delegate, where the Func<dynamic, object> first argument to the method is a dynamic variable of type, and we can get the value of the variable parameter in the URL from that variable.

Example:/products/{productname}

    public class ProductModule : NancyModule    {        public ProductModule()        {            Get("/products/{productName}", p => p.productName);        }    }

Fragments with nullable variables (Capture segment-optional)

The URL parameter in Nancy also supports nullable types, just add a question mark after the parameter.

Example:/products/{productname?}

    public class ProductModule : NancyModule    {        public ProductModule()        {            Get("/products/{productName?}", p => p.productName == null ? "Missing the name" : p.productName);        }    }

Nancy can also set a default value for parameters of nullable types, which can be placed after the question mark.

Example:/products/{productname?defaultname}

    public class ProductModule : NancyModule    {        public ProductModule()        {            Get("/products/{productName?defaultName}", p => p.productName);        }    }

Regular fragment (RegEx Segment)

You can also use regular expressions in Nancy's routing templates.

Example:/products/(? [\d]{2,}]

    public class ProductModule : NancyModule    {        public ProductModule()        {            Get(@"/products/(?<productId>[\d]{2,})", p => "Your product id is " + p.productId);        }    }

This regular means that only integers with more than 2 digits are allowed.

Greedy fragments (greedy Segment)

Nancy can append an asterisk at the end of the variable to indicate that all strings match from the current position to the ending of the URL.

Example:/products/{productname*}

    public class ProductModule : NancyModule    {        public ProductModule()        {            Get("/products/{productName*}", p => p.productName);        }    }

Now let's take the asterisk off and look at the difference.

Example:/products/{productname}

Cannot match to any route template.

Priority level

In ASP. We will use the route template defined by the Maproute method, and when there is a request, the MVC handler will match according to the order of the routing template we define, and if the match succeeds, it will go into the corresponding action method to process the request.

So how do you determine the matching order of the templates in Nancy's non-configurable framework?

In Nancy, for several routing fragment types that are provided by default, Nancy provides a template score (Pattern scoring), and the higher the template score, the better the priority match.

Scores for several basic template types in Nancy

Templates score
Plain text fragment (Literal Segment) 10000
Fragment with variable (Capture Segment) 1000
Fragments with nullable variables (Capture segment-optional) 1000
Regular fragment (RegEx Segment) 1000
Greedy regular fragment (greedy RegEx Segment) 100
Multivariate fragment (multiple Captures Segment) 100
Greedy fragments (greedy Segment) 0

Example: There are currently 2 route template "/products/{productname}" and "/products/coffee", we request the URL is/products/coffee, the result is as follows

    public class ProductModule : NancyModule    {        public ProductModule()        {            Get("/products/{productName}", p => p.productName);            Get("/products/coffee", p => "Hello Coffee.");        }    }

This is because the priority level of a plain text fragment is higher than the fragment containing the variable, so the current request is processed preferentially.

Route fragment parameter type constraint

Nancy can also constrain parameter types in the routing template. The format of the constraint is "{variable name: Constraint type}".

Example: "/products/{productid:int}"

    public class ProductModule : NancyModule    {        public ProductModule()        {            Get("/products/{productId:int}", p => "Product id is " + p.productId);        }    }

When the constraint matches, the request succeeds.

When the constraints do not match, the request fails.

General constraints

The following general constraint types are available in Nancy.

Constraint Type Explanatory notes
Int Only Int32 numbers are allowed
Long Only Int64 numbers are allowed
Decimal Allow only decimals
Guid Only GUID allowed
bool Only Allow True/false
Alpha Only letters allowed
Datetime Allow only time
DateTime (format) Allow only specific format times
Min (mininum) Minimum allowable integer value
Max (Maxinum) Maximum allowable integer value
Range (Mininum, maxinum) Allowable range of integer values
MinLength (length) allowable minimum length of string
MaxLength (length) Maximum allowable length of a string
Length (length) Allowable range of string lengths
Version Only allow version number, example 1.0.0
Custom Constraints

In Nancy, you can RouteSegmentConstraintBase define constraints by inheriting and ParameterizedRouteSegmentConstraintBase customizing them.

Routesegmentconstraintbase -accumulation of constrained conditions without parameters
Parameterizedroutesegmentconstraintbase -base class with parameter constraints

Below we create an email constraint ourselves.
First we create a EmailRouteSegmentConstraint class and inherit the RouteSegmentConstraintBase class, whose code is as follows

    public class EmailRouteSegmentConstraint : RouteSegmentConstraintBase<string>    {        public override string Name        {            get { return "email"; }        }        protected override bool TryMatch(string constraint, string segment, out string matchedValue)        {            if (segment.Contains("@"))            {                matchedValue = segment;                return true;            }            matchedValue = null;            return false;        }    }

Where the Trymatch method indicates that an attempt is made to determine if the parameter matches, and if True is the match, false is the match failure. The Name property represents the names of the current constraints.

We create a new StaffModule class whose code is as follows

    public class StaffModule : NancyModule    {        public StaffModule()        {            Get("/staff/{email:email}", p => "Your email is " + p.email);        }    }

Below we launch the project, enter/staff/lamondlu@qq.com in the browser, the request is processed correctly.

At this point, if we enter/STAFF/LAMONDLU in the browser, the system will return 404.

Conditional constraints in Nancy (Condition)

Some conditional constraints on requests can also be implemented in Nancy.

For example, the current request is processed when the submitted form contains an email field and the value of the email field is lamondlu@qq.com.

    public class StaffModule : NancyModule    {        public StaffModule()        {            Post("/staff", p => "Submited", p => p.Request.Form.email == "lamondlu@qq.com");        }    }

Here I add the third parameter condition, condition is a Func<NancyContext, bool> type of delegate, from Nancycontext we can get all the information requested. Here I read the email field from the request form, and if the value of the email field is lamondlu@qq.com, Nancy will return a submited text.

Let's use postman to test it.
First we do not include any fields in the form, and the request results are as follows.

We then add the email field to the form and the value is lamondlu@qq.com, and the request results are as follows.

The request was processed correctly.

The above is the entire contents of the Nancy Routing section, and interested students can add my qq:309728709 to study together, next time I will share the view engine in Nancy.

Attached source code


Lamond Lu
Source: www.cnblogs.com/lwqlun/p/9607652.html
This site uses the "Attribution 4.0 International" Creative sharing agreement, please indicate the author and source in the obvious position of the article.

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.