nancyfx-to create small WebAPI and Microservice

Source: Internet
Author: User
Tags define get hosting

In the non-web-site integration, I love to use a trick: Write a Process to provide WebAPI interface to other system calls, no matter what you use the language ghost platform, how can not find httpcllient components or libraries? Ogochi for a few years, dare you tell me that you will not write the program of call Web page? You see, a lot of straight and strong, on the mainstream trend we stand on the high point, High banner Web API, the world is not enemy, wow haha ~ this is very good?

Do not run ASP. NET directly in IIS, mostly because the program has authorization or special restrictions (for example: integration of heavyweight interactive applications such as Word, Excel), usually I will write as Console application or Windows Service, so need to have The Self-host module provides basic building blocks such as TCP connections, routing, and Request/response. I've studied some solutions, such as:

    • I write from TCP
      Microhttpserver-Write an HTTP Server in 100 lines C #
    • Using the ASP. NET Web API self-host
      The ASP. NET Web API is not possible without IIS

From the head has been written, purely for fun experience is OK, to get to the ease of use of the realm is afraid to bleed, and there are repeated to build the heavy suspicion of the wheel. I encountered a lot of small WebAPI in the context of the situation, often only one to two APIs, moving out of the powerful full set of ASP. Self-host always gave me the feeling of killing chicken with sledgehammer, not in accordance with the KISS (Keep It Simple, Stupid) central thought. Recently tried to play Nancyfx, amazed by the nature, simple is the mini WebAPI dapper! Presumably, after a few days, we'll be using it in a lot of places.

Subscribe to a super-simple topic: a WebAPI that generates a new GUID each time. Take a look at how many steps and number of travel codes are required to actually do this with NANCYFX.

First we open a Console application case, with the NuGet installation Nancy.Hosting.Self kit (Nancy will install it too):

Declares a nancymodule guidgeneratormodule, constructed in the get["/"] definition Lambda function to return Guid.NewGuid (). ToString (). This 様 WebAPI the part of the Request is finished, then the part of the self-hosting, in Main () set up a nancyhost, specify the link URL, call Start () can open business. Reminder: Windows 7+ needs to be licensed as a manager (less recommended) or with Netsh http add urlacl url=http://+:32767/user=machine\username.

typography shows pure text
Using Nancy;
Using Nancy.Hosting.Self;
Using System;
Namespace Nancyfxdemo
{
    Class Program
    {
        void Main (string[] args)
        {
            New Nancyhost (
                New Uri ("http://localhost:9527" )))
            {
                Host. Start ();
                Console.WriteLine ("Press any key to stop ...");
                Console.read ();
                Host. Stop ();
            }
        }
    }
    Class Guidgeneratormodule:nancymodule
    {
        Public Guidgeneratormodule ()
        {
            get["/"] = (p) = =
            {
                Return Guid.NewGuid (). ToString ();
            };
        }
    }
}

Ginger ginger Ginger Ginger ~ accidentally we wrote WebAPI! So short and so short, it's my dish. No mistake: P

The last supplement is a few common uses:

1. Get the parameters by routetypography shows pure text
            Get the parameters by URL route
            get["Route/{blah}" = (p) = =
            {
                "Param=" + p.blah.tostring ();
            };

In the route using the {blah} indicator, P.blah is the content (or p["blah")

2. Define get and Post, get the parameters from Form and QueryStringtypography shows pure text
            Read the parameters by QueryString or form
            get["concat"] = post["concat"] = (p)  = =
            {
                Query, form is dynamic, which can be written as query.a or query["A"
                Query.blah return type is Dynamicdictionaryvalue, HasValue and value
                String. Format ("{0} {1}",
                    
                    request.query["B"]. Value?? request.form[String. Empty); 
            };

Nancy's Request also has Query and form, but unlike ASP. rquest["blah"] take-all QueryString, Form and Cookie, the above program I show use?? Operator (called the Null Union operator, null-coalescing Operator) All-in-one Query and Form. And as how to make the GET and POST sharing method,

The results are as follows:

GET

POST

Snap ~ Pen Pineapple Apple pen ...

3.Model Binding

If you think it's too low to use request.form/query, it's hard not to fall for Nancy. After adding the using nancy.modelbinding, call this. The bind<t> can bind the parameters to a predetermined model type object.

typography shows pure text
        Class Concatparams
        {
            String A {get; set;}
            String B {get; set;}
        }
        Public Guidgeneratormodule ()
        {
            get["Concatbymodel"] = post["Concatbymodel"] = (p)  = =
            {
                This. Bind<concatparams> ();
                String. Format ("{0} {1}", Param. A, Param. B);
            };
        }

4.POST JSON and Echo JSON

The following shows how to receive the JSON content of the POST and the JSON back:

typography shows pure text
            post["Concatbyjson"] = (p) = =
            {
                This. Bind<concateparams> ();
                Return Response.asjson (new
                {
                    String. Format ("{0} {1}", Param. A, Param. B)
                });
            };

The Magical Bind (), in addition to being able to object from Query and Form, can directly deserialize the JSON string of the POST into objects, while Response.asjson () supports serializing the object into a JSON string without any force.

In addition to the above-mentioned simplicity, Nancy also supports many web site standard functions such as: identity verification, beforerequest/onerror events, customized bug pages ... And even with Razor to write a View, it's not difficult to make a Web site that does not iis+asp.net MVC. But according to my strategy, the complex web site will still choose to use ASP. NET MVC, to join the WebAPI function on the Console application/wpf/windows Service This is a close to the meat Bo, the nancyfx of this sharp Short wepons, with two DLLs plus a few stroke-type second kill demand.

nancyfx-to create small WebAPI and Microservice

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.