创建用户c#时读取超时错误

时间:2015-06-14 19:34:33

标签: c# entity-framework asp.net-web-api

创建/编辑用户时出现这个奇怪的错误。 错误如下所示:

  

从' ReadTimeout'获取值时出错on' Microsoft.Owin.Host.SystemWeb.CallStreams.InputStream'。

fiddler中的错误是:

{
  "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)"
  }
}

我试图找出导致它的原因,但我无法找到问题。 这是我的创建功能:

/// <summary>
/// Creates a user
/// </summary>
/// <param name="model">The bound user model</param>
/// <returns></returns>
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> CreateUser(UserBindingModel model)
{

    // Save our user to the database
    return Ok(await Save(model));
}

/// <summary>
/// Used to save a user
/// </summary>
/// <param name="model">The model representing the user</param>
/// <returns></returns>
private async Task<IHttpActionResult> Save(UserBindingModel model)
{

    // If our ModelState is invalid, return a bad request
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    // Get the current userId and date
    var userId = User.Identity.GetUserId();
    var date = DateTime.UtcNow;

    // Assign our binding model to a new model
    var user = new User()
    {
        CompanyId = model.CompanyId,
        UserName = model.Email,
        Email = model.Email,
        FirstName = model.FirstName,
        LastName = model.LastName,
        LastLoginDate = date,
        Telephone = model.Telephone,

        CreatedById = string.IsNullOrEmpty(model.CreatedById) ? userId : model.CreatedById,
        DateCreated = string.IsNullOrEmpty(model.CreatedById) ? date : model.DateCreated,
        ModifiedById = userId,
        DateModified = date
    };

    // Create our result
    var result = new IdentityResult();

    // If we don't have a created by id
    if (string.IsNullOrEmpty(model.CreatedById))
    {

        // Try to create the user
        result = await this.UserService.CreateAsync(user);

        // Send our the confirmation email
        await SendConfirmationEmail(user.Id);
    }
    else // Else
    {

        // Try to update the user
        result = await this.UserService.UpdateAsync(user);
    }

    // If the creation fails, return the error
    if (!result.Succeeded)
        return GetErrorResult(result);

    // Return the result
    return Ok(this.ModelFactory.Create(user));
}

/// <summary>
/// Used to send a confirmation email to the user specified
/// </summary>
/// <param name="userId">The id of the user we wish to send an email to</param>
/// <returns></returns>
private async Task SendConfirmationEmail(string userId)
{            
    // Generate our unique code
    var code = await this.UserService.GenerateEmailConfirmationTokenAsync(userId);

    // Create the callback url
    var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = userId, code = code }).Replace("api/users", "#/account"));

    // Send the email
    await this.UserService.SendEmailAsync(userId, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
}

有没有人之前有这个错误或知道是什么原因导致的? 我用谷歌搜索了所有错误似乎与UserManager绑定,这很奇怪,但没有人有任何答案。

1 个答案:

答案 0 :(得分:0)

这通常发生在最终通过Web API返回之前“双重包装”或嵌套结果时,您看到的异常是JSON序列化命中内部结果的不受支持的属性。

要解决此问题,请查看返回IHttpActionResult的所有方法。我很困惑为什么你在代码中包含CreateUser方法,因为它似乎没有被Save方法使用,这最初是我怀疑你的问题。如果您在CreateUser方法中 调用了Save并尝试返回结果,那么您将进行双重包装。