我正在为我的客户开发一个中间件,发现在执行该过程时会有一些延迟。
我们目前正在研究从架构设计到编码的问题的确切原因。
下面是我们调用的脚本的一部分,只是想知道代码本身是否已经过优化和正确编写?
以下代码中存在无错误,只是想知道是否存在性能或编码问题。 TKS
public string getResponse(System.Type type, Object input, string taskName, string method)
{
string response = string.Empty;
try
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(type);
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, input);
string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
using (WebClient webClient = new WebClient())
{
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
logger.Info("Sending [" + method + "] request to API[" + string.Format(Configuration.getTargetURI(), taskName) + "]");
response = webClient.UploadString(string.Format(Configuration.getTargetURI(), taskName), method, data);
logger.Info("Response of API[" + string.Format(Configuration.getTargetURI(), taskName) + "] successfully retrieved");
logger.Debug("Response: " + response);
}
}
catch (Exception ex)
{
logger.Info("Failed to invoke [" + method + "] request to API[" + string.Format(Configuration.getTargetURI(), taskName) + "], Error: " + ex.Message);
logger.Error(ex.Message + ex.StackTrace);
throw ex;
}
return response;
}
public string getResponseNoInput(string taskName, string method)
{
string response = string.Empty;
try
{
WebRequest req = WebRequest.Create(String.Format(Configuration.getTargetURI(), taskName));
req.Method = method;
req.ContentType = "application/json; charset=utf-8";
logger.Info("Sending [" + method + "] request to API[" + string.Format(Configuration.getTargetURI(), taskName) + "]");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
response = sr.ReadToEnd();
}
logger.Info("Response of API[" + string.Format(Configuration.getTargetURI(), taskName) + "] successfully retrieved");
logger.Debug("Response: " + response);
}
catch(Exception ex)
{
logger.Info("Failed to invoke [" + method + "] request to API[" + string.Format(Configuration.getTargetURI(), taskName) + "], Error: " + ex.Message);
logger.Error(ex.Message + ex.StackTrace);
throw ex;
}
return response;
}