asp.net 개발 위 챗 공식 플랫폼 의 검증 메시지 의 진실성

메시지 의 진실성 을 검증 하 다
MVC Controller 가 있 는 항목 에 필 터 를 추가 하고 필터 에 다시 쓰기
public override void OnActionExecuting(ActionExecuting Context filter Context)방법
새 데이터 모델

주:서버 가 메 시 지 를 받 을 때 signature 가 아니 라 msgsignature
위 챗 서버 에서 서버 로 메 시 지 를 전송 하 는 HTTP 요청 메시지 예제
POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6×tamp=1409659813&nonce=1372623149 HTTP/1.1
Host: qy.weixin.qq.com
방법 재 작성,메시지 검증 실현
위 챗 접속 시 검증 하 는 방법 을 호출 하지만 매개 변 수 는 조금 바 꾸 고 새로운 데이터 모델 을 사용 해 야 합 니 다.


Action 방법 이나 Controller 에 필터 속성 추가

코드 예제
Model

/// <summary>
  ///         
  /// </summary>
  public class WeChatMsgRequestModel
  {
    public string timestamp { get; set; }
    public string nonce { get; set; }

    public string msg_signature { get; set; }
  }

Filter

public class WeChatRequestValidAttribute : ActionFilterAttribute
  {
    private const string Token = "StupidMe";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      //    
      Model.FormatModel.WeChatMsgRequestModel model = new Model.FormatModel.WeChatMsgRequestModel() { nonce= filterContext.HttpContext.Request.QueryString["nonce"],msg_signature= filterContext.HttpContext.Request.QueryString["msg_signature"],timestamp= filterContext.HttpContext.Request.QueryString["timestamp"] };
      //  
      if (CheckSignature(model))
      {
        base.OnActionExecuting(filterContext);
      }      
    }

    private bool CheckSignature(Model.FormatModel.WeChatMsgRequestModel model)
    {
      string signature, timestamp, nonce, tempStr;
      //        
      signature = model.msg_signature;
      timestamp = model.timestamp;
      nonce = model.nonce;
      //    ,  Token, timestamp, nonce         
      string[] array = { Token, timestamp, nonce };
      //    
      Array.Sort(array);
      //        
      tempStr = String.Join("", array);
      //       SHA1  
      tempStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tempStr, "SHA1").ToLower();
      //  signature     
      if (tempStr.Equals(signature))
      {
        return true;
      }
      else
      {
        return false;
      }
    }
  }

Controller Code

/// <summary>
    ///     
    /// </summary>
    private static Common.LogHelper logger = new Common.LogHelper(typeof(HomeController));

    [Filters.WeChatRequestValid]
    public void Valid(Model.FormatModel.WeChatMsgRequestModel model)
    {
      if (ModelState.IsValid)
      {
        try
        {
          //     POST  
          if (HttpContext.Request.HttpMethod.ToUpper() == "POST")
          {
            //              
            using (Stream stream = HttpContext.Request.InputStream)
            {
              byte[] postBytes = new byte[stream.Length];
              stream.Read(postBytes, 0, (int)stream.Length);
              string postString = System.Text.Encoding.UTF8.GetString(postBytes);
              Handle(postString,model);
            }
          }
        }
        catch (Exception ex)
        {
          logger.Error("    ,    :" + ex.Message + ex.StackTrace);
        }
      }
    }      

이상 에서 말 한 것 이 바로 본문의 전체 내용 이 니 여러분 들 이 좋아 하 시 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기