加入收藏 | 设为首页 | 会员中心 | 我要投稿 南平站长网 (https://www.0599zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > Asp教程 > 正文

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

发布时间:2020-08-21 13:08:57 所属栏目:Asp教程 来源:网络整理
导读:副标题#e# AutoWrapper是一个简单可自定义全局异常处理程序和ASP.NET Core API响应的包装。他使用ASP.NET Core middleware拦截传入的HTTP请求,并将最后的结果使用统一的格式来自动包装起来.目的主要是让我们更多的关注业务特定的代码要求,并让包装器自动

public class MyCustomApiResponse { public int Code { get; set; } public string Message { get; set; } public object Payload { get; set; } public DateTime SentDate { get; set; } public Pagination Pagination { get; set; } public MyCustomApiResponse(DateTime sentDate, object payload = null, string message = "", int statusCode = 200, Pagination pagination = null) { this.Code = statusCode; this.Message = message == string.Empty ? "Success" : message; this.Payload = payload; this.SentDate = sentDate; this.Pagination = pagination; } public MyCustomApiResponse(DateTime sentDate, object payload = null, Pagination pagination = null) { this.Code = 200; this.Message = "Success"; this.Payload = payload; this.SentDate = sentDate; this.Pagination = pagination; } public MyCustomApiResponse(object payload) { this.Code = 200; this.Payload = payload; } } public class Pagination { public int TotalItemsCount { get; set; } public int PageSize { get; set; } public int CurrentPage { get; set; } public int TotalPages { get; set; } }

通过如下代码片段进行测试结果

public async Task<MyCustomApiResponse> Get() { var data = await _personManager.GetAllAsync(); return new MyCustomApiResponse(DateTime.UtcNow, data, new Pagination { CurrentPage = 1, PageSize = 10, TotalItemsCount = 200, TotalPages = 20 }); }

运行后会得到如下影响格式

{ "code": 200, "message": "Success", "payload": [ { "id": 1, "firstName": "Vianne", "lastName": "Durano", "dateOfBirth": "2018-11-01T00:00:00" }, { "id": 2, "firstName": "Vynn", "lastName": "Durano", "dateOfBirth": "2018-11-01T00:00:00" }, { "id": 3, "firstName": "Mitch", "lastName": "Durano", "dateOfBirth": "2018-11-01T00:00:00" } ], "sentDate": "2019-10-17T02:26:32.5242353Z", "pagination": { "totalItemsCount": 200, "pageSize": 10, "currentPage": 1, "totalPages": 20 } }

但是从这里要注意一旦我们对API响应进行自定义,那么就代表我们完全控制了要格式化数据的方式,同时丢失了默认API响应的某些选项配置。但是我们仍然可以利用ApiException()方法引发用户定义的错误消息

如下所示

[Route("{id:long}")] [HttpPut] public async Task<MyCustomApiResponse> Put(long id, [FromBody] PersonDTO dto) { if (ModelState.IsValid) { try { var person = _mapper.Map<Person>(dto); person.ID = id; if (await _personManager.UpdateAsync(person)) return new MyCustomApiResponse(DateTime.UtcNow, true, "Update successful."); else throw new ApiException($"Record with id: {id} does not exist.", 400); } catch (Exception ex) { _logger.Log(LogLevel.Error, ex, "Error when trying to update with ID:{@ID}", id); throw; } } else throw new ApiException(ModelState.AllErrors()); }

现在当进行模型验证时,可以获得默认响应格式

{ "isError": true, "responseException": { "exceptionMessage": "Request responded with validation error(s). Please correct the specified validation errors and try again.", "validationErrors": [ { "field": "FirstName", "message": "'First Name' must not be empty." } ] } }

Reference

https://github.com/proudmonkey/AutoWrapper

到此这篇关于ASP.NET Core AutoWrapper 自定义响应输出实现的文章就介绍到这了,更多相关ASP.NET Core AutoWrapper响应输出内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

(编辑:南平站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读