瀏覽代碼

added model validation filter

tags/v0.1.0
Robin Thoni 8 年之前
父節點
當前提交
53c1d88f1d

+ 7
- 6
Luticate2.Utils/Controllers/LuCrudController.cs 查看文件

@@ -1,4 +1,5 @@
1
-using Luticate2.Utils.Dbo.Basic;
1
+using System.ComponentModel.DataAnnotations;
2
+using Luticate2.Utils.Dbo.Basic;
2 3
 using Luticate2.Utils.Dbo.Filter;
3 4
 using Luticate2.Utils.Dbo.OrderBy;
4 5
 using Luticate2.Utils.Interfaces;
@@ -21,14 +22,14 @@ namespace Luticate2.Utils.Controllers
21 22
 
22 23
         [HttpGet]
23 24
         [Route("[controller]/{id}")]
24
-        public LuApiWrapperDbo<TDboRead> GetSingleById(TId id)
25
+        public LuApiWrapperDbo<TDboRead> GetSingleById([Required]TId id)
25 26
         {
26 27
             return Handle(Busines.GetSingleById(id));
27 28
         }
28 29
 
29 30
         [HttpGet]
30 31
         [Route("[controller]")]
31
-        public LuApiWrapperDbo<LuPaginatedDbo<TDboRead>> GetMultiple(LuOrderByDbo orderBy, LuFilterDbo filter,
32
+        public LuApiWrapperDbo<LuPaginatedDbo<TDboRead>> GetMultiple([Required]LuOrderByDbo orderBy, LuFilterDbo filter,
32 33
             int page = 0, int perPage = int.MaxValue)
33 34
         {
34 35
             return Handle(Busines.GetMultiple(orderBy, filter, page, perPage));
@@ -36,21 +37,21 @@ namespace Luticate2.Utils.Controllers
36 37
 
37 38
         [HttpPost]
38 39
         [Route("[controller]")]
39
-        public LuApiWrapperDbo<TDboRead> AddDbo([FromBody]TDboCreate data)
40
+        public LuApiWrapperDbo<TDboRead> AddDbo([FromBody][Required]TDboCreate data)
40 41
         {
41 42
             return Handle(Busines.AddDbo(data));
42 43
         }
43 44
 
44 45
         [HttpPost]
45 46
         [Route("[controller]/{id}")]
46
-        public LuApiWrapperDbo<TDboRead> EditSingleByIdDbo(TId id, [FromBody]TDboUpdate data)
47
+        public LuApiWrapperDbo<TDboRead> EditSingleByIdDbo([Required]TId id, [FromBody][Required]TDboUpdate data)
47 48
         {
48 49
             return Handle(Busines.EditSingleByIdDbo(id, data));
49 50
         }
50 51
 
51 52
         [HttpDelete]
52 53
         [Route("[controller]/{id}")]
53
-        public LuApiWrapperDbo<TDboRead> Delete(TId id)
54
+        public LuApiWrapperDbo<TDboRead> Delete([Required]TId id)
54 55
         {
55 56
             return Handle(Busines.DeleteSingleByIdDbo(id));
56 57
         }

+ 1
- 0
Luticate2.Utils/Controllers/LuUtilsExtensions.cs 查看文件

@@ -59,6 +59,7 @@ namespace Luticate2.Utils.Controllers
59 59
                 {
60 60
                     options.ModelBinderProviders.Insert(0, new LuOrderByBinderProvider());
61 61
                     options.ModelBinderProviders.Insert(0, new LuFilterBinderProvider());
62
+                    options.Filters.Add(typeof(LuModelStateFilter));
62 63
                 });
63 64
             return builder;
64 65
         }

+ 3
- 2
Luticate2.Utils/Dbo/OrderBy/LuOrderByBinder.cs 查看文件

@@ -14,9 +14,9 @@ namespace Luticate2.Utils.Dbo.OrderBy
14 14
                 data = "";
15 15
             }
16 16
             data = data.Trim();
17
-            var dbo = new LuOrderByDbo {Fields = new List<LuOrderByFieldDbo>()};
18 17
             if (data != "")
19 18
             {
19
+                var dbo = new LuOrderByDbo {Fields = new List<LuOrderByFieldDbo>()};
20 20
                 var fields = data.Split(',');
21 21
                 foreach (var field in fields)
22 22
                 {
@@ -49,8 +49,9 @@ namespace Luticate2.Utils.Dbo.OrderBy
49 49
                     }
50 50
                     dbo.Fields.Add(value);
51 51
                 }
52
+                return LuResult<LuOrderByDbo>.Ok(dbo);
52 53
             }
53
-            return LuResult<LuOrderByDbo>.Ok(dbo);
54
+            return LuResult<LuOrderByDbo>.Error(LuStatus.InputError, "Order by is empty or missing", "");
54 55
         }
55 56
 
56 57
         public Task BindModelAsync(ModelBindingContext bindingContext)

+ 66
- 0
Luticate2.Utils/Middlewares/LuModelStateFilter.cs 查看文件

@@ -0,0 +1,66 @@
1
+using System.ComponentModel.DataAnnotations;
2
+using System.Linq;
3
+using System.Reflection;
4
+using Luticate2.Utils.Controllers;
5
+using Luticate2.Utils.Dbo.Result;
6
+using Microsoft.AspNetCore.Mvc.Controllers;
7
+using Microsoft.AspNetCore.Mvc.Filters;
8
+using Microsoft.AspNetCore.Mvc.ModelBinding;
9
+
10
+namespace Luticate2.Utils.Middlewares
11
+{
12
+    public class LuModelStateFilter : IActionFilter
13
+    {
14
+        public void OnActionExecuting(ActionExecutingContext context)
15
+        {
16
+            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
17
+
18
+            if (descriptor != null)
19
+            {
20
+                var parameters = descriptor.MethodInfo.GetParameters();
21
+
22
+                foreach (var parameter in parameters)
23
+                {
24
+                    var argument = context.ActionArguments.ContainsKey(parameter.Name) ? context.ActionArguments[parameter.Name] : null;
25
+
26
+                    EvaluateValidationAttributes(parameter, argument, context.ModelState);
27
+                }
28
+            }
29
+
30
+            if (!context.ModelState.IsValid)
31
+            {
32
+                var errors = "";
33
+                foreach (var key in context.ModelState.Keys)
34
+                {
35
+                    var error = " " + key + ": " + context.ModelState[key]
36
+                        .Errors.Select(modelError => modelError.ErrorMessage)
37
+                        .Aggregate((s, s1) => s + ", " + s1);
38
+                    errors += error;
39
+                }
40
+                throw new LuResultException(LuResult<object>.Error(LuStatus.InputError, "Validation error:" + errors, ""));
41
+            }
42
+        }
43
+
44
+        private void EvaluateValidationAttributes(ParameterInfo parameter, object argument, ModelStateDictionary modelState)
45
+        {
46
+            foreach (var attributeData in parameter.CustomAttributes)
47
+            {
48
+                var validationAttribute = parameter.GetCustomAttribute(attributeData.AttributeType) as ValidationAttribute;
49
+
50
+                if (validationAttribute != null)
51
+                {
52
+                    var isValid = validationAttribute.IsValid(argument);
53
+                    if (!isValid)
54
+                    {
55
+                        modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name));
56
+                    }
57
+                }
58
+            }
59
+        }
60
+
61
+        public void OnActionExecuted(ActionExecutedContext context)
62
+        {
63
+
64
+        }
65
+    }
66
+}

+ 1
- 5
TestUtils/Binders/LuOrderByBinderTest.cs 查看文件

@@ -11,11 +11,7 @@ namespace TestUtils.Binders
11 11
         {
12 12
             var res = LuOrderByBinder.FromString("");
13 13
             Assert.NotNull(res);
14
-            Assert.Equal(LuStatus.Success, res.Status);
15
-            var dbo = res.Data;
16
-            Assert.NotNull(dbo);
17
-            Assert.NotNull(dbo.Fields);
18
-            Assert.Equal(0, dbo.Fields.Count);
14
+            Assert.Equal(LuStatus.InputError, res.Status);
19 15
         }
20 16
 
21 17
         [Fact]

+ 1
- 2
WebApiUtils/Startup.cs 查看文件

@@ -5,7 +5,6 @@ using Microsoft.EntityFrameworkCore;
5 5
 using Microsoft.Extensions.Configuration;
6 6
 using Microsoft.Extensions.DependencyInjection;
7 7
 using Microsoft.Extensions.Logging;
8
-using TestUtils;
9 8
 using TestUtils.DataAccess;
10 9
 using WebApiUtils.Business;
11 10
 
@@ -38,7 +37,7 @@ namespace WebApiUtils
38 37
             // Add framework services.
39 38
             services.AddApplicationInsightsTelemetry(Configuration);
40 39
 
41
-            services.AddLuticateUtils(options => options.Version = "sdev");
40
+            services.AddLuticateUtils(options => options.Version = "dev");
42 41
 
43 42
             services.AddTransient<PkGuidBusiness>();
44 43
             services.AddTransient<LuUtilsPkGuidDataAccess>();

Loading…
取消
儲存