使异步调用形成通用处理程序

使异步调用形成通用处理程序

本文介绍了使异步调用形成通用处理程序(.ashx)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网站上有一个表单,将json发布到async处理程序,该处理程序验证数据并返回响应OK或错误,我将根据我的处理程序给出的响应在客户端上进行重定向。



但是当响应确定后,我想异步执行一些任务。但异步调用在.ashx代码中不起作用。它总是同步的。



你可以给我一个建议吗?



代码: p>

  public class ValidateHandler:IHttpHandler,IRequiresSessionState 
{

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


foreach(nvcForm.AllKeys中的string nameValueKey)
{
regExpToTest = string.Empty;
switch(nameValueKey)
{
casefirstName:
// validate
break;
caselastName:
// validate
break;
caseemail:
// validate
break;
casephoneNumber:
// validate
break;
casephoneCountryCode:
//验证
break;
casecountry:
// validate
break;
caseaddressLine1:
// validate
break;
caseaddressLine2:
// validate
break;
casecity:
// validate
break;
casepostalCode:
// validate
break;
默认值:
//验证
break;
}
if(!string.IsNullOrEmpty(regExpToTest)&!Regex.IsMatch(nvcForm [nameValueKey],regExpToTest)&!string.IsNullOrEmpty(nvcForm [nameValueKey]))
{
errorFieldsDict.Add(nameValueKey,请输入正确的值);
isSuccess = false;
}
}

//在这里做你的业务逻辑,最后

if(isSuccess)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
try
{
字典< 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,合作伙伴);
string brochureType = string.Empty;
if(!string.IsNullOrEmpty(nvcForm [addressLine1])||!string.IsNullOrEmpty(nvcForm [addressLine2]))
brochureType =FBRO;
else
brochureType =EBRO;
//在数据库
中创建一个项目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(查询处理程序失败:+ 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));
}

}
私有字符串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()

}
}
私人字典< string,object> GetDictionaryForJson(NameValueCollection formValues)
{
字典< string,object> formDictionary = new Dictionary< string,object>();
foreach(formValues.AllKeys中的字符串键)
{
formDictionary.Add(key,formValues [key]);
}

return formDictionary;
}

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

PS:我确实隐藏了一些只是我们业务的代码。但是如果你可以评论



谢谢你们

解决方案

你需要注意 IHttpAsyncHandler 而不是 IHttpHandler 并将其注册在web.config文件中。浏览器还将观察连接限制,因此请确保IIS配置正确以处理多个连接,保持活动等。



以下详细介绍:


I have a form in my website which posts json to the async handler which validates the data and return back the resonse OK or error and i will make the redirect on the client based on the response give by my handler.

But when the response is ok, i want to perform some tasks asynchronously. But the asynchronous calls are not working inside the .ashx code. it is always synchronous.

Could you please give me an advice on this.?

code:

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: I did hide some code which is just our business.But Would be great if you can comment on that.

thanks guys

解决方案

You need to implmement IHttpAsyncHandler rather than IHttpHandler and register it as such in the web.config file. Browsers will also observe connection limits, so make sure IIS is configured properly to handle multiple connections, keep-alive, etc.

Here's a detailed walk through: http://msdn.microsoft.com/en-us/library/ms227433.aspx

这篇关于使异步调用形成通用处理程序(.ashx)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:03