gpt4 book ai didi

c# - 通过Json Formatter引发异常时,如何在ASP.NET Web Api中全局处理异常

转载 作者:行者123 更新时间:2023-12-03 07:49:45 25 4
gpt4 key购买 nike

我们使用WebApi2和AngularJs开发ASP.NET MVC5应用程序。对于序列化和反序列化,我们使用custum 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数据时会出错。我的问题是我们如何处理这些错误并发送给客户端?

错误示例:

enter image description here

最佳答案

您可以创建自己的自定义异常处理程序,以在将其发送到客户端之前修改所有错误消息。

    public class ErrorHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{

context.Result = new TextPlainErrorResult()
{
Request = context.ExceptionContext.Request,
Content = "Oops! Sorry! Something went wrong." + "Please contact support so we can try to fix it."
};
}

private class TextPlainErrorResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }

public string Content { get; set; }

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError, Content);
return Task.FromResult(response);
}
}
}

然后在配置类中注册此自定义类,如下所示
config.Services.Replace(typeof(IExceptionHandler), new ErrorHandler());

关于c# - 通过Json Formatter引发异常时,如何在ASP.NET Web Api中全局处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39039789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com