Files
simapi-net/Controllers/SimApiBaseController.cs
T

91 lines
2.8 KiB
C#
Raw Permalink Normal View History

2020-08-05 15:29:56 +08:00
using SimApi.Communications;
2019-12-23 16:32:06 +08:00
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Linq;
2020-08-05 15:29:56 +08:00
using SimApi.Exceptions;
using SimApi.Attributes;
2019-12-23 16:32:06 +08:00
2020-08-05 15:29:56 +08:00
namespace SimApi.Controllers
2019-12-23 16:32:06 +08:00
{
/// <summary>
/// 基础控制器,所有控制器均继承本控制器
/// 1. 自动验证请求参数
/// 2. 报错返回
/// 3. 错误回馈页面
/// </summary>
2020-08-05 15:29:56 +08:00
public class SimApiBaseController : Controller
2019-12-23 16:32:06 +08:00
{
2019-12-27 17:28:14 +08:00
/// <summary>
/// 当前登录用户的ID
/// </summary>
2020-08-05 15:29:56 +08:00
protected SimApiLoginItem LoginInfo => (SimApiLoginItem)HttpContext.Items["LoginInfo"];
2019-12-23 16:32:06 +08:00
/// <summary>
/// 验证请求参数
/// </summary>
/// <param name="context"></param>
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
foreach (var item in context.ModelState.Values)
{
if (item.ValidationState == ModelValidationState.Invalid)
{
Error(400, item.Errors.First().ErrorMessage);
break;
}
}
}
}
/// <summary>
/// 错误返回
/// </summary>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述(若是常规错误,代码可自动带取描述)</param>
/// <returns></returns>
2020-12-29 17:39:06 +08:00
protected static void Error(int code = 500, string message = "")
2019-12-23 16:32:06 +08:00
{
2020-08-05 15:29:56 +08:00
throw new SimApiException(code, message);
2019-12-23 16:32:06 +08:00
}
/// <summary>
/// 检测条件,根据条件返回报错
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
2020-12-29 17:39:06 +08:00
protected static void ErrorWhen(bool condition, int code = 500, string message = "")
2019-12-23 16:32:06 +08:00
{
if (condition)
{
Error(code, message);
}
}
2020-01-17 12:40:22 +08:00
/// <summary>
/// 检测给定的变量是否为NUll
/// </summary>
/// <param name="condition">检测条件</param>
/// <param name="code">错误代码</param>
/// <param name="message">错误描述</param>
2020-12-29 17:39:06 +08:00
protected static void ErrorWhenNull(object condition, int code = 404, string message = "")
2020-01-17 12:40:22 +08:00
{
ErrorWhen(condition == null, code, message);
}
2019-12-23 16:32:06 +08:00
/// <summary>
2020-07-05 06:09:02 +08:00
/// 上传文件
2019-12-23 16:32:06 +08:00
/// </summary>
/// <returns></returns>
2020-08-05 15:29:56 +08:00
protected SimApiBaseResponse<string> UploadFile()
2020-01-17 12:40:22 +08:00
{
2020-08-05 15:29:56 +08:00
return new SimApiBaseResponse<string>();
2020-01-17 12:40:22 +08:00
}
2020-07-05 06:09:02 +08:00
2020-08-05 15:29:56 +08:00
2019-12-23 16:32:06 +08:00
}
}