using EC.App.Entity;
using EC.App.Factory;
using Furion.DataValidation;
using Furion.DependencyInjection;
using Furion.UnifyResult;
using Furion.UnifyResult.Internal;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;
namespace EC.App.Extensions
{
///
/// 返回值
///
[SuppressSniffer, UnifyModel(typeof(RespParam<>))]
public class RespParamProvider : IUnifyResultProvider
{
///
/// 成功返回值
///
///
///
///
public IActionResult OnSucceeded(ActionExecutedContext context, object data)
{
return RespParamFactory.New(StatusCodes.Status200OK, true, data).ToJsonResult();
}
///
/// 验证失败返回值
///
///
///
///
public IActionResult OnValidateFailed(ActionExecutingContext context, ValidationMetadata metadata)
{
return RespParamFactory.New(StatusCodes.Status400BadRequest, errors: metadata.ValidationResult).ToJsonResult();
}
///
/// 异常返回值
///
///
///
///
public IActionResult OnException(ExceptionContext context, ExceptionMetadata metadata)
{
return RespParamFactory.New(metadata.StatusCode, errors: metadata.Errors).ToJsonResult();
}
///
/// 特定状态码返回值
///
///
///
///
///
public async Task OnResponseStatusCodes(HttpContext context, int code, UnifyResultSettingsOptions unifyResultSettings = null)
{
// 设置响应状态码
UnifyContext.SetResponseStatusCodes(context, code, unifyResultSettings);
switch (code)
{
// 处理 401 状态码
case StatusCodes.Status401Unauthorized:
await context.Response.WriteAsJsonAsync(RespParamFactory.New(code, errors: "401 Unauthorized")
, Furion.App.GetOptions()?.JsonSerializerOptions);
break;
// 处理 403 状态码
case StatusCodes.Status403Forbidden:
await context.Response.WriteAsJsonAsync(RespParamFactory.New(code, errors: "403 Forbidden")
, Furion.App.GetOptions()?.JsonSerializerOptions);
break;
default: break;
}
}
}
}