C# 服务器发送响应所花费的时间太长-ASP.NET Web API中出现超时错误
我已经创建了一个在服务器上运行的Web API应用程序。在客户端,为了进行测试,我使用了android应用程序。 这很简单。用户输入用户名和密码,并用另外两个字符串DeviceId和DeviceName发送它们。 用户通过已定义的服务进行验证,如果一切顺利,将发生3件事:C# 服务器发送响应所花费的时间太长-ASP.NET Web API中出现超时错误,c#,regex,asp.net-mvc,asp.net-web-api,server-response,C#,Regex,Asp.net Mvc,Asp.net Web Api,Server Response,我已经创建了一个在服务器上运行的Web API应用程序。在客户端,为了进行测试,我使用了android应用程序。 这很简单。用户输入用户名和密码,并用另外两个字符串DeviceId和DeviceName发送它们。 用户通过已定义的服务进行验证,如果一切顺利,将发生3件事: 用户被创建并保存在数据库中 信息电子邮件发送给用户 访问令牌返回给客户端 但在我的代码中做了一些更改之后,服务器的响应开始花费太长时间,对于移动用户来说,超时发生得太频繁 我注意到,在添加代码的一个特定部分后,超时开始发生:
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
string deviceId = rgx.Replace(model.DeviceId, "");
此部分用于从DeviceID字符串中修剪所有非字母数字字符。这一点很重要,因为在添加此代码之前,如果用户在此变量中有斜杠或反斜杠,则会出现与JSON相关的错误
所以我的问题是:是否有可能Regex类及其方法在服务器上造成一些混乱,并使服务器的响应时间过长
如果有任何帮助,这是有问题呼叫的代码:
[Route("registration/request")]
public async Task<HttpResponseMessage> RegistrationRequest(Registration model)
{
try
{
MatrixLogManager.Info("Starting token creating.");
var request = HttpContext.Current.Request;
var tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "/Token";
MatrixLogManager.Info("Checking if model is valid.");
if (!ModelState.IsValid)
{
return Request.CreateResponse(BadRequest(ModelState));
}
using (MatrixServiceLayerLogin login = new MatrixServiceLayerLogin())
{
if (login.LoginUser(model.UserName, model.Password, true, true))
{
var personId = login.GetPersonId();
MatrixLogManager.Debug("User " + model.UserName + " successfully logged in on MatrixSTS.");
try
{
using (var authRepo = new AuthRepository())
{
MatrixLogManager.Info("Changing deviceID format.");
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
model.DeviceId = rgx.Replace(model.DeviceId, "");
MatrixLogManager.Debug(model.DeviceId);
MatrixLogManager.Debug("Saving user: " + model.DeviceId);
ApplicationUser appUser = new UserFactory().CreateApplicationUser(model, personId);
IdentityResult result = await authRepo.RegisterUser(appUser);
EMailService.SendEmail(appUser);
IHttpActionResult errorResult = GetErrorResult(result);
MatrixLogManager.Debug("Saved user: " + model.DeviceId);
if (errorResult != null)
{
return Request.CreateResponse(errorResult);
}
using (var client = new HttpClient())
{
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", appUser.UserName),
new KeyValuePair<string, string>("password", "0000")
};
var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
var tokenServiceResponse = await client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded);
var responseString = await tokenServiceResponse.Content.ReadAsStringAsync();
var responseCode = tokenServiceResponse.StatusCode;
var responseMsg = new HttpResponseMessage(responseCode)
{
Content = new StringContent(responseString, Encoding.UTF8, "application/json")
};
responseMsg.Headers.Add("PSK", appUser.PSK);
return responseMsg;
}
}
}
catch (Exception ex)
{
MatrixLogManager.Error("Error: ", ex);
throw ex;
}
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid username or password.");
}
}
}
catch (Exception ex)
{
MatrixLogManager.Error(string.Format("Error while trying registring user: Exception = {0} InnerException {1}", ex.Message, ex.InnerException.Message));
throw;
}
}
[路线(“注册/请求”)]
公共异步任务注册请求(注册模型)
{
尝试
{
MatrixLogManager.Info(“开始创建令牌”);
var request=HttpContext.Current.request;
var tokenServiceUrl=request.Url.GetLeftPart(UriPartial.Authority)+request.ApplicationPath+“/Token”;
MatrixLogManager.Info(“检查模型是否有效。”);
如果(!ModelState.IsValid)
{
returnrequest.CreateResponse(BadRequest(ModelState));
}
使用(MatrixServiceLayerlLogin login=new MatrixServiceLayerlLogin())
{
if(login.LoginUser(model.UserName、model.Password、true、true))
{
var personId=login.GetPersonId();
MatrixLogManager.Debug(“用户”+model.UserName+“成功登录MatrixSTS”);
尝试
{
使用(var authRepo=new AuthRepository())
{
MatrixLogManager.Info(“更改设备ID格式”);
正则表达式rgx=新正则表达式(“[^a-zA-Z0-9-]”);
model.DeviceId=rgx.Replace(model.DeviceId,“”);
MatrixLogManager.Debug(model.DeviceId);
MatrixLogManager.Debug(“保存用户:“+model.DeviceId”);
ApplicationUser appUser=new UserFactory().CreateApplicationUser(模型,personId);
IdentityResult结果=等待authRepo.RegisterUser(appUser);
EMailService.sendmail(appUser);
IHttpActionResult errorResult=GetErrorResult(结果);
MatrixLogManager.Debug(“保存的用户:“+model.DeviceId”);
if(errorResult!=null)
{
返回请求.CreateResponse(errorResult);
}
使用(var client=new HttpClient())
{
var requestParams=新列表
{
新的KeyValuePair(“授权类型”、“密码”),
新的KeyValuePair(“用户名”,appUser.username),
新的KeyValuePair(“密码”,“0000”)
};
var requestParamsFormUrlEncoded=新FormUrlEncodedContent(requestParams);
var tokenServiceResponse=Wait client.PostAsync(tokenServiceUrl,requestParamsFormUrlEncoded);
var responseString=await-tokenservicesponse.Content.ReadAsStringAsync();
var responseCode=tokenservicesponse.StatusCode;
var responseMsg=新的HttpResponseMessage(响应代码)
{
Content=newstringcontent(responseString,Encoding.UTF8,“application/json”)
};
添加(“PSK”,appUser.PSK);
返回响应;
}
}
}
捕获(例外情况除外)
{
MatrixLogManager.Error(“Error:,ex”);
掷骰子;
}
}
其他的
{
返回请求.CreateErrorResponse(HttpStatusCode.Unauthorized,“无效的用户名或密码”);
}
}
}
捕获(例外情况除外)
{
MatrixLogManager.Error(string.Format(“尝试注册用户时出错:异常={0}InnerException{1}”,例如Message,例如InnerException.Message));
投掷;
}
}
还有一件事。当我在我的机器上测试这段代码时,本地响应时间并不长,而且一切都很顺利。问题只在将此代码发布到服务器时才会出现,而且这种情况时有发生。我在这里看到两个问题:
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
model.DeviceId = rgx.Replace(model.DeviceId, "");
首先,通过使用正则表达式构造函数,每次应用正则表达式对象时,都会强制系统创建一个新的正则表达式对象。如果改用其中一个静态方法,系统会在您第一次使用Regex对象时自动缓存它。或者可以提前构造正则表达式并将其存储在静态变量中
其次,你一次替换一个不需要的字符,这是非常低效的。在正则表达式的末尾添加一个+
,以便一次匹配不需要的字符的整个序列
model.DeviceId = Regex.Replace(model.DeviceId, "[^a-zA-Z0-9 -]+", "");
我认为regex不应该受到责备,除非你每秒有1000个ping。最佳实践(我的最佳实践)是