• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

ASP.NET Core AutoWrapper 自定义响应输出实现

c# 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

前言

AutoWrapper是一个简单可自定义全局异常处理程序和ASP.NET Core API响应的包装。他使用ASP.NET Core middleware拦截传入的HTTP请求,并将最后的结果使用统一的格式来自动包装起来.目的主要是让我们更多的关注业务特定的代码要求,并让包装器自动处理HTTP响应。这可以在构建API时加快开发时间,同时为HTTP响应试试我们统一的标准。

安装

AutoWrapper.Core从NuGet或通过CLI下载并安装

PM> Install-Package AutoWrapper.Core 

在Startup.cs Configure方法中注册以下内容,但是切记要放在UseRouting前

app.UseApiResponseAndExceptionWrapper(); 

启动属性映射

默认情况下AutoWrapper将在成功请求成功时输出以下格式:

{
  "message": "Request successful.",
  "isError": false,
  "result": [
   {
    "id": 7002,
    "firstName": "Vianne",
    "lastName": "Durano",
    "dateOfBirth": "2018-11-01T00:00:00"
   }
  ]
}

如果说不喜欢默认属性命名来4源gaodaimacom搞#代%码*网方式,那么我们可以通过AutoWrapperPropertyMap属性进行映射为我们需要指定的任何名称。例如我么可以将result属性的名称更改为data。如下所示

public class MapResponseObject 
{
  [AutoWrapperPropertyMap(Prop.Result)]
  public object Data { get; set; }
}

然后将MapResponseObject类传递给AutpWrapper middleware

app.UseApiResponseAndExceptionWrapper<MapResponseObject>(); 

通过映射重新请求后,现在影响格式如下所示

{
  "message": "Request successful.",
  "isError": false,
  "data": {
    "id": 7002,
    "firstName": "Vianne",
    "lastName": "Durano",
    "dateOfBirth": "2018-11-01T00:00:00"
  }
}

可以从中看出result属性已经更换为data属性了

默认情况下AutoWrapper发生异常时将吐出以下响应格式

{
  "isError": true,
  "responseException": {
    "exceptionMessage": "Unhandled Exception occurred. Unable to process the request."
  }
}

而且如果在AutoWrapperOptions中设置了IsDebug,则将产生带有堆栈跟踪信息的类似信息

{
  "isError": true,
  "responseException": {
    "exceptionMessage": " Input string was not in a correct format.",
    "details": "  at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)\r\n  at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)\r\n …"
  }
}

如果想将某些APIError属性名称更改为其他名称,只需要在以下代码中添加以下映射MapResponseObject

public class MapResponseObject 
{
  [AutoWrapperPropertyMap(Prop.ResponseException)]
  public object Error { get; set; }

  [AutoWrapperPropertyMap(Prop.ResponseException_ExceptionMessage)]
  public string Message { get; set; }

  [AutoWrapperPropertyMap(Prop.ResponseException_Details)]
  public string StackTrace { get; set; }
}

通过如下代码来模拟错误

int num = Convert.ToInt32("10s"); 

现在映射后的输出如下所示

{
  "isError": true,
  "error": {
    "message": " Input string was not in a correct format.",
    "stackTrace": "  at System.Number.ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type)\r\n  at System.Number.ParseInt32(ReadOnlySpan`1 value, NumberStyles styles, NumberFormatInfo info)\r\n …"
  }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:ASP.NET Core AutoWrapper 自定义响应输出实现

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址