title: Error: System.InvalidOperationException in ASP.NET WebAPI
body: <p>I'm trying to enter some data into database and get access_token on the end of successful call. </p>
  
  <p>When I make a call passing this parameters:</p>
  
  <p><img src="https://i.stack.imgur.com/AIJ4m.png" alt="enter image description here"></p>
  
  <p>Everything goes fine, user gets registered and saved into database, and access_token returns to user:</p>
  
  <p><img src="https://i.stack.imgur.com/i0Qvk.png" alt="enter image description here"></p>
  
  <p>But, when I add signs +, = or \ in the deviceId value I get exception and nothing get saved in database:</p>
  
  <p><img src="https://i.stack.imgur.com/pUjbQ.png" alt="enter image description here"></p>
  
  <p><img src="https://i.stack.imgur.com/jVfhN.png" alt="enter image description here"></p>
  
  <pre><code>{
      "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&amp; memberContract, Object&amp; 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.&lt;BufferResponseContentAsync&gt;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)"
      }
  }
  </code></pre>
  
  <p>This is model definition for this call:</p>
  
  <pre><code>public class Registration
      {
          public string UserName { get; set; }
          public string Password{ get; set; }
          public string DeviceId { get; set; }
          public string DeviceName { get; set; }
      }
  </code></pre>
  
  <p>Field deviceId gets saved into database as UserName, and by it's definition it is NVARCHAR(1024)</p>
  
  <p><img src="https://i.stack.imgur.com/j9LSL.png" alt="enter image description here"></p>
  
  <p>Is it possible that NVARCHAR doesn't allow characters that are not letters and numbers? Did someone else had problem like this? </p>
  
  <p>EDIT: This is the method where the problem is:</p>
  
  <pre><code>[Route("registration/request")]
  public async Task&lt;HttpResponseMessage&gt; 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&lt;KeyValuePair&lt;string, string&gt;&gt;
                                                  {
                                                      new KeyValuePair&lt;string, string&gt;("grant_type", "password"),
                                                      new KeyValuePair&lt;string, string&gt;("username", appUser.UserName),
                                                      new KeyValuePair&lt;string, string&gt;("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;
      }
  }
  </code></pre>
  
  <p>Try-Catch does not catch any exception, the real exception happens here:</p>
  
  <pre><code>public async Task&lt;IdentityResult&gt; RegisterUser(ApplicationUser userModel)
  {
      userModel.TwoFactorEnabled = true;
      userModel.PSK = TimeSensitivePassCode.GeneratePresharedKey();
  
      var result = await _userManager.CreateAsync(userModel, "0000");
  
      return result;
  }
  </code></pre>
  
  <p>When the line where the result is returns to client. I've gues that saving in line before doesn't go well. I will set try-catch in that part of code and I will post exception.</p>