C# 错误:ASP.NET WebAPI中的System.InvalidOperationException

C# 错误:ASP.NET WebAPI中的System.InvalidOperationException,c#,asp.net,asp.net-web-api,C#,Asp.net,Asp.net Web Api,我正在尝试将一些数据输入数据库,并在成功调用结束时获取access_令牌 当我通过此参数进行调用时: 一切正常,用户注册并保存到数据库中,access_令牌返回给用户: 但是,当我在deviceId值中添加符号+、=或\时,我会得到异常,数据库中不会保存任何内容: { "message": "An error has occurred.", "exceptionMessage": "Error getting value from 'ReadTimeout' on 'Micr

我正在尝试将一些数据输入数据库,并在成功调用结束时获取access_令牌

当我通过此参数进行调用时:

一切正常,用户注册并保存到数据库中,access_令牌返回给用户:

但是,当我在deviceId值中添加符号+、=或\时,我会得到异常,数据库中不会保存任何内容:

{
    "message": "An error has occurred.",
    "exceptionMessage": "Error getting value from 'ReadTimeout' on 'Microsoft.Owin.Host.SystemWeb.CallStreams.InputStream'.",
    "exceptionType": "Newtonsoft.Json.JsonSerializationException",
    "stackTrace": "   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n   at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<BufferResponseContentAsync>d__13.MoveNext()",
    "innerException": {
        "message": "An error has occurred.",
        "exceptionMessage": "Timeouts are not supported on this stream.",
        "exceptionType": "System.InvalidOperationException",
        "stackTrace": "   at System.IO.Stream.get_ReadTimeout()\r\n   at Microsoft.Owin.Host.SystemWeb.CallStreams.DelegatingStream.get_ReadTimeout()\r\n   at GetReadTimeout(Object )\r\n   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
    }
}

字段deviceId作为用户名保存到数据库中,根据其定义,它是NVARCHAR(1024)

NVARCHAR是否可能不允许使用非字母和数字的字符?其他人有这样的问题吗

编辑:这是问题所在的方法:

[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())
                    {
                        ApplicationUser appUser = new UserFactory().CreateApplicationUser(model, personId);
                        IdentityResult result = await authRepo.RegisterUser(appUser);
                        EMailService.SendEmail(appUser);
                        IHttpActionResult errorResult = GetErrorResult(result);

                        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())
{
ApplicationUser appUser=new UserFactory().CreateApplicationUser(模型,personId);
IdentityResult结果=等待authRepo.RegisterUser(appUser);
EMailService.sendmail(appUser);
IHttpActionResult errorResult=GetErrorResult(结果);
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));
投掷;
}
}
Try-Catch不捕获任何异常,真正的异常发生在这里:

public async Task<IdentityResult> RegisterUser(ApplicationUser userModel)
{
    userModel.TwoFactorEnabled = true;
    userModel.PSK = TimeSensitivePassCode.GeneratePresharedKey();

    var result = await _userManager.CreateAsync(userModel, "0000");

    return result;
}
公共异步任务注册服务器(ApplicationUser userModel)
{
userModel.twofacturenabled=true;
userModel.PSK=TimeSensitivePassCode.GeneratePresharedKey();
var result=await_userManager.CreateAsync(userModel,“0000”);
返回结果;
}

当结果所在的行返回到客户端时。我以前也说过,排队存钱不太好。我将在代码的这一部分设置try-catch,并发布异常。

我看不到您的完整实现,但如果我进行了有根据的猜测,您可能会尝试调用您的登录例程,该例程返回一个HttpResponseMessage数据类型(从您的注册例程中)。这两种方法都使用Request.CreateResponse来创建响应

请看,问题是,您正在尝试序列化已序列化的HttpResponseMessage。您的登录方法将调用Request.CreateResponse来创建HttpResponseMessage,您可能只是将它转过来并“传递”到您的注册方法(但可能会通过另一个Request.CreateResponse方法调用来传递它,这正是您遇到麻烦的地方)。这是一个“隐性”错误,很难抓住——就像一个棋手盯着棋盘看了几个小时

现在来看解决方案: 只需将login方法的结果作为register方法的结果传递,而无需通过Request.CreateResponse方法对其进行“处理”。如果您是Rest返回状态代码的纯粹主义者,您可以在返回Register方法之前首先更改返回的状态代码(因为登录可能有一个OK[200]的状态代码),而在Register Rest end p中返回CREATED[201]是更好的做法
public async Task<IdentityResult> RegisterUser(ApplicationUser userModel)
{
    userModel.TwoFactorEnabled = true;
    userModel.PSK = TimeSensitivePassCode.GeneratePresharedKey();

    var result = await _userManager.CreateAsync(userModel, "0000");

    return result;
}
return Request.CreateResponse(errorResult);
[Route("registration/request")]
public async Task<IHttpResult> 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 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())
                    {
                        ApplicationUser appUser = new UserFactory().CreateApplicationUser(model, personId);
                        IdentityResult result = await authRepo.RegisterUser(appUser);
                        EMailService.SendEmail(appUser);
                        IHttpActionResult errorResult = GetErrorResult(result);

                        if (errorResult != null)
                        {
                            // MAJOR CHANGE here
                            return 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;
    }
}