【问题标题】:JsonSerializationError not correctly handled by middleware中间件未正确处理 JsonSerializationError
【发布时间】:2019-09-05 14:50:10
【问题描述】:

我遇到了一个非常奇怪的错误。

我有一个带有一些 JsonRequired 属性的项目。

当我在缺少一个必需的属性时尝试调用我的路由来获取我的项目时,我的错误不会自动抛出为错误代码 500,而是得到 200 Ok。

这是我的路线:

[HttpGet("{itemId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<Item>> GetItemByIdAsync(long installationId, Guid itemId)
    {
        return await _itemService.GetItemByIdAsync(installationId, itemId);
    }

这是我的 Item 类:

public class Item
{
    [JsonProperty("id")]
    [JsonRequired]
    public Guid Id { get; set; }

    [JsonProperty("name")]
    [JsonRequired]
    public string Name { get; set; }
}

这是我的中间件:

public async Task Invoke(HttpContext context)
{
        try
        {
            await _next(context);
        }
        catch (NotFoundException ex)
        {
            await HandleExceptionAsync(context, HttpStatusCode.NotFound, ex);
        }
        catch (UnauthorizedException ex)
        {
            await HandleExceptionAsync(context, HttpStatusCode.Unauthorized, ex, false);
        }
        catch (ConflictException ex)
        {
            await HandleExceptionAsync(context, HttpStatusCode.Conflict, ex);
        }
        catch (BadRequestException ex)
        {
            await HandleExceptionAsync(context, HttpStatusCode.BadRequest, ex);
        }
    }

private Task HandleExceptionAsync(HttpContext context, HttpStatusCode httpCode, Exception exception, bool displayException = true)
{
        _logger.LogError(exception, $"Exception catched in middleware: {exception.Message}.");

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)httpCode;

        var payload = JsonConvert.SerializeObject(new ApiError(displayException ? exception.Message : string.Empty));

            return context.Response.WriteAsync(payload);
}

我尝试过的: 如果我尝试在中间件中添加这个捕获

catch (Exception ex)
    {
        await HandleExceptionAsync(context, HttpStatusCode.InternalServerError, ex);
    }

仍然有相同的结果,我没有收到 500 错误。 我真的不明白为什么我的响应没有被覆盖为 500 错误。 你有什么想法吗?

非常感谢。

【问题讨论】:

  • 500 错误说明了什么?你检查过回复的正文吗?
  • 问题是我没有收到 500 错误,正文是空的。中间件未处理 JsonSerializationException。
  • 关于外发回复?您假设列表为空,因此应该抛出?
  • 或者该项为空?
  • 我认为this 可能会解决您的问题

标签: c# asp.net-core-webapi asp.net-core-2.2


【解决方案1】:

因为你没有显示你的_itemService.GetItemByIdAsync。当我用下面的代码进行测试时它工作得很好,它有一个 500 错误。

public async Task<ActionResult<Item>> GetItemByIdAsync()
    {
        string json = @"{
          'id': '2f5135a7-977c-4b26-a4e2-74b9e374a75e',
          'name': null,

        }";

        Item x = JsonConvert.DeserializeObject<Item>(json);//throw 500 error using your Item model
        return x;
    }

您也可以将Required 属性用于 JsonProperty 之类的

[JsonProperty("name", Required = Required.Always)] //could not be null       
public string Name { get; set; }

它的定义是:

    //
// Summary:
//     Indicating whether a property is required.
public enum Required
{
    //
    // Summary:
    //     The property is not required. The default state.
    Default = 0,
    //
    // Summary:
    //     The property must be defined in JSON but can be a null value.
    AllowNull = 1,
    //
    // Summary:
    //     The property must be defined in JSON and cannot be a null value.
    Always = 2,
    //
    // Summary:
    //     The property is not required but it cannot be a null value.
    DisallowNull = 3
}

【讨论】:

  • 感谢您的回复。我会尝试你的建议。但我在 _itemService.GetItemById 中没有收到任何错误,它返回一个 Item ,其属性 id 已填充,名称为 null。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
  • 2012-09-09
  • 2020-07-23
  • 2014-08-31
  • 2014-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多