.NET Core RESTful API
1.RESTful 是指架构风格,并不是约束
2.建议URI的规范性
api/companies/{id}/employees/{id}
3.http方法 get,post ,put,patch,delete
post必须知道Content-Type
4.状态码明确:
200 成功
201 返回结果
204 返回成功 无结果
406 notaccepteable
5.Model Bind
FromQuery,FromBody,FromRoute,FromForm
6.验证规则
使用Model上面的Reuqired,MAxLength Atrribute信息
或者自定义实现IValidatableObject,ValidationAtrribute
都存在时候上面优先级高
7.异常处理
/// <summary> /// api异常统一处理过滤器 /// 系统级别异常 500 应用级别异常501 /// </summary> public class ApiExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(ExceptionContext context) { context.Result = BuildExceptionResult(context.Exception); base.OnException(context); } /// <summary> /// 包装处理异常格式 /// </summary> /// <param name="ex"></param> /// <returns></returns> private JsonResult BuildExceptionResult(Exception ex) { int code = 0; string message = ""; string innerMessage = ""; //应用程序业务级异常 if (ex is ApplicationException) { code = 501; message = ex.Message; } else { // exception 系统级别异常,不直接明文显示的 code = 500; message = "发生系统级别异常"; innerMessage = ex.Message; } if (ex.InnerException != null && ex.Message != ex.InnerException.Message) innerMessage += "," + ex.InnerException.Message; return new JsonResult(new { code, message, innerMessage }); } }

浙公网安备 33010602011771号