在 IIS 中运行站点时从“CompiledAssembly”获取值时出错,在 Visual Studio 中正常

Der*_*rek 4 c# serialization json routedata

我正在运行一个 MVC 项目并利用 Json,我的代码在 Visual Studio 中运行时可以正常运行,然后我在 IIS 上有一个指向同一文件夹的站点,当从 IIS 站点执行 URL 时,我的代码没有执行方式与在 Visual Studio 中相同。

在我的代码中,我有:

return JsonConvert.SerializeObject(objectToSerialize);
Run Code Online (Sandbox Code Playgroud)

当我发送 RouteData.Values 时,它会产生以下错误:

Error getting value from 'CompiledAssembly' on 'System.CodeDom.Compiler.CompilerResults'.

at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonConvert.SerializeObjectInternal(Object value, Type type, JsonSerializer jsonSerializer)
at Newtonsoft.Json.JsonConvert.SerializeObject(Object value)
at x.Data.Helpers.Data.JsonHelper.SerializeObject(Object objectToSerialize) in D:\Development\x\x.Data\Helpers\Data\JsonHelper.cs:line 18
Run Code Online (Sandbox Code Playgroud)

我目前正在使用Newtonsoft.Json, Version=11.0.0.0

有什么想法吗?IIS 没有 Visual Studio 具备的功能吗?

小智 7

我最近遇到了同样的异常,但原因不同。您的 RouteData.Values 对象是一个RouteValueDictionary,可以将对象作为值,其中一些对象可能具有在调用“get”时引发异常的属性。

您可以通过传入 JsonSerializerSettings 对象作为第二个参数并重写 Error EventHandler 来处理这些问题。

如果您只想忽略此类属性,将 ErrorEventArgs.ErrorContext.Handled 设置为 true 应该可以解决问题。

return JsonConvert.SerializeObject(objectToSerialize, new JsonSerializerSettings() { Error = new EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs>((obj, args) => {
                args.ErrorContext.Handled = true;
            }) });
Run Code Online (Sandbox Code Playgroud)