Micro-credit Public platform development Course (iii) basic framework to build _c# tutorial

Source: Internet
Author: User
Tags http request sha1 sha1 encryption

First of all, we designed the module level diagram, of course, the diagram is only given a way to achieve, not limited to this. See the figure below.

The main functions are as follows:

1 Request interface layer. Processing HTTP requests, and responding

2) Distribution layer. Incoming requests from the interface layer and then analyze the request type to distribute to different processors

3 Business Logic layer. Here is our specific business logic, according to the request, the implementation of specific business logic.

4) Data layer. When implementing an application, we may need to access the data, either a database or a file. If it is a simple application, it may not have this layer.

In fact, the specific application can be expanded in this structure, can extend the Message object layer, business object layer, data access layer, function management layer and so on. Here is just a way of thinking, not limited to this.


According to the level diagram, the design flow chart, specifically describes the implementation of each process. To understand the entire process. As shown in the following illustration:


According to the flow chart, we can clearly understand the whole process, the details of the implementation of message processing steps.

Here we implement the code for each process.

First, receive HTTP requests

We need a HttpHandler or a Web page to handle the HTTP request on the micro-service side.

Here we use the HttpHandler. Because of its high flexibility, good performance.

Concretely implemented as follows.

public class Weixinhttphandler:ihttphandler
  {
    ///<summary>
    /// 
    ///</summary>
    public bool IsReusable
    {get
      {true;}
    }
    <summary>
    ///processing request
    ///</summary>
    ///<param name= "context" ></param> Public
    void ProcessRequest (HttpContext context)
    {
      //by the micro-credit service to receive the request, the specific processing request
      Weixinservice Wxservice = new Weixinservice (context. Request);
      String responsemsg = Wxservice.response ();
      Context. Response.Clear ();
      Context. Response.Charset = "UTF-8";
      Context. Response.Write (responsemsg);
      Context. Response.End ();
    }
  

If it is HttpHandler, you need to configure the specific application in the configuration file. Specific node configuration, we do not make a statement. Give an example directly, configure the HttpHandler node as follows

 
 

II. Distribution of requests

For functional encapsulation, we also encapsulate this in the processing component. In fact, it can be placed in the HttpHandler.

1) Verifying signatures

If this is the first request, you need to verify the signature. is equivalent to an HTTP handshake. Previously in the previous chapter, set the server URL and the token value, this function is to verify that the link is successful.

This request is a GET request. The following specific description (official):

Business logic:

Encryption/validation Process:

<1> sort token, timestamp, nonce three parameters in dictionary order

<2> concatenation of three parameter strings into a string for SHA1 encryption

<3> developers get encrypted strings that can be compared to signature, identifying the request from a micro-letter

But the official only provides the PHP code example, many things in C # are not literal translation. So there are some specific treatment. Read the official code first:

Private Function Checksignature ()
  {
    $signature = $_get["signature"];
    $timestamp = $_get["timestamp"];
    $nonce = $_get["nonce"];  
        
    $token = token;
    $TMPARR = Array ($token, $timestamp, $nonce);
    Sort ($TMPARR);
    $TMPSTR = implode ($TMPARR);
    $TMPSTR = SHA1 ($TMPSTR);
    
    if ($tmpStr = = $signature) {return
      true;
    } else{return
      false;
    }
  

We will translate it into C # version:

<summary>
    ///Check signature
    ///</summary>
    ///<param name= "Request" ></param>
    // /<returns></returns>
    private bool Checksignature ()
    {
      string signature = Request.QueryString [SIGNATURE];
      string timestamp = Request.querystring[timestamp];
      String nonce = Request.querystring[nonce];

      list<string> list = new list<string> ();
      List. ADD (TOKEN);
      List. ADD (timestamp);
      List. ADD (nonce);
      Sort
      list. Sort ();
      Puzzle
      String input = string. Empty;
      foreach (var item in list)
      {
        input = = Item;
      }
      Encrypted
      string new_signature = Securityutility.sha1encrypt (input);
      Verify
      if (new_signature = = signature)
      {return
        true;
      }
      else
      {return
        false;
      }
    }

This requires SHA1 encryption, the specific algorithm is as follows:

<summary>
    ///SHA1 encryption
    ///</summary>
    ///<param name= "intput" > Input string </param>
    ///<returns> Encrypted string </returns> public
    static string Sha1encrypt (String intput)
    {
      byte[ ] Strres = Encoding.Default.GetBytes (intput);
      HashAlgorithm Mysha = new SHA1CryptoServiceProvider ();
      Strres = Mysha.computehash (strres);
      StringBuilder entext = new StringBuilder ();
      foreach (byte in strres)
      {
        Entext.appendformat ("{0:x2}", byte);
      return entext.tostring ();
    }

2) Distribution Request

The next step is a specific message request, all of which are post requests.

Because there are a variety of message types, we encapsulate them through the factory class, and each message has a specialized processor for processing. Specific implementation logic:

<summary>
    ///processing request
    ///</summary>
    ///<returns></returns>
    Private String responsemsg ()
    {
      string requestxml = Common.readrequest (this. Request);
      Ihandler handler = Handlerfactory.createhandler (requestxml);
      if (handler!= null)
      {return
        handler. HandleRequest ();
      }

      return string. Empty;
    }

The external method of processing the request (this is the HttpHandler call method), namely:

<summary>
    ///processing requests, generating responses
    ///</summary>
    ///<returns></returns>
    Public String Response ()
    {
      string method = Request.HttpMethod.ToUpper ();
      Verify that
      the signature if (method = = ' Get ')
      {
        if (checksignature ())
        {return
          request.querystring[echostr];
        }
        Else
        {return
          ' error ';
        }
      }

      Process message
      if (method = = "POST")
      {return
        responsemsg ()
      }
      else
      {return
        ' cannot be processed ';
      }
    }

Third, the message processor specific processing messages

1) Message type

First we look at the specific message type, in fact the previous one has been explicitly given to the interface of the message.

Look at the details here, what type of message is requested, what type of message to reply to, and so on.

Must pay attention, the request message is the text type, the reply message, is not necessarily also the text oh, may be the picture, the music and so on any kind can reply the message. See the table below for details.


2 Design the message class according to the specific message interface.

The class diagram is given here for reference.

3 for different messages, there will be different processors, to see the specific class diagram.

4) Specific Business processing

Within each handler, a specific request can be processed. What messages you enter, access those data, call services, and so on, are handled here.

It is also recommended that you encapsulate the specific business separately, and in handler, only provide the interface that is invoked.

Because with the increase in business, a handler may have to deal with a lot of business, if all the operational logic is written here, it is bound to affect reading, and not easy to maintain and expand.

5) Generate reply message

After processing the request, you need to generate a reply message that responds to the terminal. Message format, that is, we introduce those message types, but must be available for reply, currently supported by: text, graphics, music and so on.

Be sure to be clear: the message type of the reply is not necessarily the same as the requested message type, for example, the request is text, the reply can be graphics and text, music.

The process of generating a reply message, in fact, is the process of formatting a particular message object into the corresponding XML, and then responding the XML to the micro-server.

6) Example

It focuses on the public account, and then the server handles the event request, registers the user, and prompts for a welcome message.

Class Eventhandler:ihandler {///<summary>///requested XML///</summary> private string requ
    estxml {get; set;}  <summary>///Constructor///</summary>///<param name= "RequestXML" ></param> public EventHandler (String requestxml) {this.
    RequestXML = RequestXML; ///<summary>///processing request///</summary>///<returns></returns> public string HandleRequest () {string response = string.
      Empty;
      Eventmessage em = eventmessage.loadfromxml (RequestXML); if (em.
        Event = = Eventtype.subscribe) {//registered users User user = new user (); User. OpenID = em.
        Fromusername;

        Usermanager.regester (user);
        Reply Welcome Message TextMessage TM = new TextMessage (); Tm. Tousername = em.
        Fromusername; Tm. Fromusername = em.
        Tousername; Tm.
        Createtime = Common.getnowtime (); Tm. Content = "You are welcome to focus on XXX, I am small." Is there anything I can help you with??
        "; Response = TM.
      Generatecontent ();
    return response;

 }
  }

Four, HTTP response

Finally, the processing results are returned to the initial HttpHandler, the response to the micro-trust server, direct response processing. This is also implemented in the HttpHandler of the first design.

The following is a code fragment, which is visible as an HTTP request

Context. Response.Clear ();
Context. Response.Charset = "UTF-8";
Context. Response.Write (responsemsg);
Context. Response.End ();

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.