Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Required Attribute not working

$
0
0

Hi,

I am working in asp.net 2.2 and i am doing model validation globally. below is code 

using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.ComponentModel.DataAnnotations; 

namespace ModelValidataionTest
{

public class UserReqTest
    {
       [Required(ErrorMessage = "Code required")]
        public string Code { get; set; }

        public UserReq userInfo;
    }

    public class UserReq

    {
        [Required(ErrorMessage = "FirstName required", AllowEmptyStrings = false)]
        public string FirstName { get; set; }


        [Required(ErrorMessage = "LastName required", AllowEmptyStrings = false)]
        public string LastName { get; set; }


        [Required(ErrorMessage = "EmailAddess required", AllowEmptyStrings = false)]
        public string EmailAddess { get; set; }


        [Required(ErrorMessage = "UserName required", AllowEmptyStrings = false)]
        public string UserName { get; set; }
}

}

//Global Validation Class 

 public class ValidateModelStateAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var problemDetails = new ValidationProblemDetails(context.ModelState)
                {
                    Instance = context.HttpContext.Request.Path,
                    Status = StatusCodes.Status400BadRequest,
                    //Type = "https://asp.net/core",
                    Detail = "Please refer to the errors property for additional details."
                };
                context.Result = new BadRequestObjectResult(problemDetails)
                {
                    ContentTypes = { "application/problem+json", "application/problem+xml" }
                };
            }
            base.OnActionExecuting(context);
        }
    }



startup.cs



  services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidateModelStateAttribute));
            });


TestController.cs

[HttpPost("UserTest")]
        public IActionResult CreateUser(UserReqTest req)
        {
            return Ok(req);
        }

I was trying to test the validation and if i dont give any value to the Property Code, its validating. sample request body

Request Body : 

{
  "userInfo": {"FirstName": "john","LastName": "Test","EmailAddess": "string","UserName": "string"
  },"Code": ""
}

Response Body :

{
  "errors": {"Code": ["Code required"
    ]
  },"title": "One or more validation errors occurred.","status": 400,"traceId": "0HLV4NQKG80L4:00000001"
}

But if the properties in the UserReq class not getting validated if its empty string. Sample Request below,

{"userInfo": {"FirstName": "","LastName": "","EmailAddess": "string","UserName": "string"
  },"Code": "Test"
}

in this case, i should get error message as first name, last name  required error. but the request gets success. not getting validated. so, basically, properties of object inside calls not getting validated. please let know how to solve this issue.


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>