2011-11-28 104 views
8

我在我的網站上有一個表單,它將json發佈到異步處理程序,它驗證數據並返回響應OK或錯誤,我將基於我的處理者給出了迴應。使異步調用形式通用處理程序(.ashx)

但是,當響應是好的,我想要異步執行一些任務。但是異步調用在.ashx代碼中不起作用。它始終是同步的。

您能否就此給我一個建議?

代碼:

public class ValidateHandler : IHttpHandler, IRequiresSessionState 
    { 

     public void ProcessRequest(HttpContext context) 
     { 
      NameValueCollection nvcForm = context.Request.Form; 
      Dictionary<string, string> errorFieldsDict = new Dictionary<string, string>(); 


      foreach (string nameValueKey in nvcForm.AllKeys) 
      { 
       regExpToTest = string.Empty; 
       switch (nameValueKey) 
       { 
        case "firstName": 
         //validate 
         break; 
        case "lastName": 
         //validate 
         break; 
        case "email": 
         //validate 
         break; 
        case "phoneNumber": 
        //validate 
         break; 
        case "phoneCountryCode": 
         //validate 
         break; 
        case "country": 
        //validate 
         break; 
        case "addressLine1": 
         //validate 
         break; 
        case "addressLine2": 
         //validate 
         break; 
        case "city": 
         //validate 
         break; 
        case "postalCode": 
         //validate 
         break; 
        default: 
         //validate 
         break; 
       } 
       if (!string.IsNullOrEmpty(regExpToTest) && !Regex.IsMatch(nvcForm[nameValueKey], regExpToTest) && !string.IsNullOrEmpty(nvcForm[nameValueKey])) 
       { 
        errorFieldsDict.Add(nameValueKey, "Please Enter Correct Value"); 
        isSuccess = false; 
       } 
      } 

      //Do your business logic here and finally 

      if (isSuccess) 
      { 
       JavaScriptSerializer serializer = new JavaScriptSerializer(); 
       try 
       { 
        Dictionary<string, object> formValues = GetDictionaryForJson(nvcForm); 
        string previoiusUrl = GetRequestedURL(context); 
        string partner = string.Empty; 
        if (System.Web.HttpContext.Current.Session["yourpartner"] != null) 
         partner = System.Web.HttpContext.Current.Session["yourpartner"].ToString(); 
        else if (System.Web.HttpContext.Current.Request.QueryString["utm_source"] != null) 
         partner = System.Web.HttpContext.Current.Request.QueryString["utm_source"]; 
        else 
         partner = "company"; 
        formValues.Add("partnerCode", partner); 
        string brochureType = string.Empty; 
        if (!string.IsNullOrEmpty(nvcForm["addressLine1"]) || !string.IsNullOrEmpty(nvcForm["addressLine2"])) 
         brochureType = "FBRO"; 
        else 
         brochureType = "EBRO"; 
        //Create a row in database 
        Item programItem = Sitecore.Context.Database.Items.GetItem(programRootpath + nvcForm["selectYourProgram"]); ; 
        AsyncMailSender caller = new AsyncMailSender(SendEmail); 
        IAsyncResult result = caller.BeginInvoke(programItem, nvcForm["email"], null, null); 
       } 
       catch (Exception ex) 
       { 
        isSuccess = false; 
        Log.Error("Enquiry handler failure: " + ex.Message, ex); 
        response.response = "error"; 
        response.message = ex.Message; 
        context.Response.ContentType = "application/json"; 
        context.Response.Write(JsonConvert.SerializeObject(response)); 
       } 
       if (isSuccess) 
       { 
        response.response = "ok"; 
        context.Response.ContentType = "application/json"; 
        context.Response.Write(JsonConvert.SerializeObject(response)); 
       } 

      } 
      else 
      { 
       response.response = "errorFields"; 
       response.errorFields = errorFieldsDict; 
       context.Response.ContentType = "application/json"; 
       string responseJson = JsonConvert.SerializeObject(response); 
       context.Response.Write(JsonConvert.SerializeObject(response, Newtonsoft.Json.Formatting.None)); 
      } 

     } 
     private string GetRequestedURL(HttpContext context) 
     { 
      string previousURL = string.Empty; 
      try 
      { 
       previousURL = context.Request.ServerVariables["HTTP_REFERER"]; 
      } 
      catch 
      { 
       previousURL = context.Request.Url.AbsolutePath; 
      } 
      return previousURL; 
     } 
     public bool IsReusable 
     { 
      get 
      { 
       return false; 
      } 
     } 
     private void SendEmail(Item programItem, string toEmail) 
     { 

      if (programItem != null) 
      { 
       SendEmail() 

      } 
     } 
     private Dictionary<string, object> GetDictionaryForJson(NameValueCollection formValues) 
     { 
      Dictionary<string, object> formDictionary = new Dictionary<string, object>(); 
      foreach (string key in formValues.AllKeys) 
      { 
       formDictionary.Add(key, formValues[key]); 
      } 

      return formDictionary; 
     } 

    } 
    public delegate void AsyncMailSender(Item program, string toAddress); 

PS:我沒有隱瞞一些代碼,只是我們business.But將是巨大的,如果你能對此作出評論。

謝謝你們

回答

6

您需要implmement IHttpAsyncHandler而不是IHttpHandler並在web.config文件中註冊它本身。瀏覽器也將觀察連接數限制,所以一定要確保IIS正確配置來處理多個連接,保活等

這裏有一個詳細的步行路程:http://msdn.microsoft.com/en-us/library/ms227433.aspx

+0

謝謝luckiffer,它的工作原理。 – sbmandav

17

在ASP.NET 4.5是HttpTaskAsyncHandler。你可以這樣使用它:

public class MyHandler : HttpTaskAsyncHandler { 

    public override async Task ProcessRequestAsync(HttpContext context) { 
     await WhateverAsync(context); 
    } 

} 
相關問題