无法将ObjectContent强制转换为HttpContent

时间:2017-09-28 12:18:55

标签: c# asp.net-web-api2

以下代码在我从笔记本电脑上的Visual Studio运行时。但是当在Windows 2016服务器上部署到IIS时,我得到500错误和异常(.NET Framework 4.7):

ExceptionMessage: "Error getting value from 'Content' on 'System.Net.Http.HttpResponseMessage'."
ExceptionType   : "Newtonsoft.Json.JsonSerializationException"

InnerException
ExceptionMessage: "Unable to cast object of type 'System.Net.Http.ObjectContent' to type 'System.Net.Http.HttpContent'."
ExceptionType   : "System.InvalidCastException"
public HttpResponseMessage Get()
{
    // Entities is the Entity Framework context
    // Sessions is a proprietary table and has nothing to do with ASP.NET sessions
    var content = new Entities().Sessions
        .AsEnumerable()
        .Select(t =>
        {
            return new
            {
                t.Id,
                t.SessionId,
                t.StartTime,
                t.EndTime
            };
        });

    return new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.OK,
        Content    = new ObjectContent(typeof(IEnumerable), content, new JsonMediaTypeFormatter())
    };
}

1 个答案:

答案 0 :(得分:0)

显然在IIS(Windows Server 2016)上使用.NET 4.7并不是一个好主意。当我将项目降级为4.6 ...

时,事情开始奏效