WebException调用dll时

时间:2011-12-12 12:23:09

标签: c# wcf

我在别人的代码中遇到了问题。我在一个项目中有代码,它调用包含相关代码的dll。

我正在调用的代码如下:

public void SaveCustomTemplate(string templateName, string templateValue)
        {
            var action = "SaveCustom";
            var webCient = new WebClient();
            var address = String.Format(urlFormat, rootUrl, action);
            var queryString = new NameValueCollection();
            queryString.Add("id",templateName);
            queryString.Add("key",apiKey);
            queryString.Add("html",templateValue);
            webCient.QueryString = queryString;

            try
            {
                webCient.UploadString(address,templateValue);
                templatesCache[templateName] = templateValue;
            }
            catch (WebException e)
            {
                var msg = String.Format("Cannot save the template '{0}'. Message:{1}.  InMessage:{2}.  Response:{3}.  Source:{4}.  Stack:{5}.  Status:{6}.  TargetSite:{7}", address, e.Message, e.InnerException.Message, e.Response, e.Source, e.StackTrace, e.Status, e.TargetSite);
                throw new WebException(msg);
            }
        }

正如您所见,我已经在其代码中进行了大量的错误处理以获取错误的来源。从这里我得到这个输出:

<div class="alert success" id="SuccessMessages">Cannot save the template 'http://localhost:30001/Templates/SaveCustom'. Message:The underlying connection was closed: An unexpected error occurred on a receive..  InMessage:Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..  Response:.  Source:System.  Stack:   at System.Net.WebClient.UploadDataInternal(Uri address, String method, Byte[] data, WebRequest& request)
   at System.Net.WebClient.UploadString(Uri address, String method, String data)
   at System.Net.WebClient.UploadString(String address, String data)
   at EmailServices.TemplateLoaders.HttpTemplateLoader.SaveCustomTemplate(String templateName, String templateValue) in C:\Projects\Red2Framework\Red2Framework\EmailServices\TemplateLoaders\HttpTemplateLoader.cs:line 94.  Status:ReceiveFailure.  TargetSite:Byte[] UploadDataInternal(System.Uri, System.String, Byte[], System.Net.WebRequest ByRef)</div>

任何帮助都将不胜感激。

由于

萨钦

1 个答案:

答案 0 :(得分:1)

您可以将UploadString用作

reply = webCient.UploadString(address, templateValue);

并跟踪服务器返回的异常。此外,您必须确保服务器不等待帖子。如果是,则使用

reply = webCient.UploadString(address, "POST", templateValue);