Browse Source

added model validation filter

tags/v0.1.0
Robin Thoni 8 years ago
parent
commit
53c1d88f1d

+ 7
- 6
Luticate2.Utils/Controllers/LuCrudController.cs View File

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

+ 1
- 0
Luticate2.Utils/Controllers/LuUtilsExtensions.cs View File

59
                 {
59
                 {
60
                     options.ModelBinderProviders.Insert(0, new LuOrderByBinderProvider());
60
                     options.ModelBinderProviders.Insert(0, new LuOrderByBinderProvider());
61
                     options.ModelBinderProviders.Insert(0, new LuFilterBinderProvider());
61
                     options.ModelBinderProviders.Insert(0, new LuFilterBinderProvider());
62
+                    options.Filters.Add(typeof(LuModelStateFilter));
62
                 });
63
                 });
63
             return builder;
64
             return builder;
64
         }
65
         }

+ 3
- 2
Luticate2.Utils/Dbo/OrderBy/LuOrderByBinder.cs View File

14
                 data = "";
14
                 data = "";
15
             }
15
             }
16
             data = data.Trim();
16
             data = data.Trim();
17
-            var dbo = new LuOrderByDbo {Fields = new List<LuOrderByFieldDbo>()};
18
             if (data != "")
17
             if (data != "")
19
             {
18
             {
19
+                var dbo = new LuOrderByDbo {Fields = new List<LuOrderByFieldDbo>()};
20
                 var fields = data.Split(',');
20
                 var fields = data.Split(',');
21
                 foreach (var field in fields)
21
                 foreach (var field in fields)
22
                 {
22
                 {
49
                     }
49
                     }
50
                     dbo.Fields.Add(value);
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
         public Task BindModelAsync(ModelBindingContext bindingContext)
57
         public Task BindModelAsync(ModelBindingContext bindingContext)

+ 66
- 0
Luticate2.Utils/Middlewares/LuModelStateFilter.cs View File

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 View File

11
         {
11
         {
12
             var res = LuOrderByBinder.FromString("");
12
             var res = LuOrderByBinder.FromString("");
13
             Assert.NotNull(res);
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
         [Fact]
17
         [Fact]

+ 1
- 2
WebApiUtils/Startup.cs View File

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

Loading…
Cancel
Save