1
提出我們開發ASP.NET MVC5應用與WebApi2和AngularJs如何在全球範圍內ASP.NET的WebAPI處理異常。序列化和反序列化,我們用俗JsonNetFormatter如下:異常時通過JsonNetFormatter
public class JsonNetFormatter : MediaTypeFormatter
{
// other codes for formatting
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
string NameOfSet = "";
ObjectWrapperWithNameOfSet obj = value as ObjectWrapperWithNameOfSet;
if (obj != null)
{
NameOfSet = obj.NameOfSet;
value = obj.WrappedObject;
}
_jsonSerializerSettings.ContractResolver = new CustomContractResolver(NameOfSet);
// Create a serializer
JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings);
// Create task writing the serialized content
return Task.Factory.StartNew(() =>
{
using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, SupportedEncodings[0])) { CloseOutput = false })
{
serializer.Serialize(jsonTextWriter, value);
jsonTextWriter.Flush();
}
});
}
}
和WebApiConfig如下:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.Formatters.Clear();
config.Formatters.Insert(0, new JsonNetFormatter());
}
}
應用做工精細。但在某些情況下,當反序列化json數據時會出現錯誤。我的問題是我們如何處理這些錯誤併發送給客戶端?
例的錯誤: