Search code examples
c#asp.net-coreasp.net-core-3.1

The string field is required. even thou there is no Required attribute in Asp.Net Core?


I am building a simple Asp.Net Core app in linux(pop os). I am using VueJs + Aps.Net Core 3.1.101 I am trying to do a POST call to my app and my model is like below:

public class AddConfigurationContextValueApiRequest
{
    public int ContextId { get; set; }

    [Required(ErrorMessage = "Value is required to continue")]
    [StringLength(500, ErrorMessage = "Value can not be longer than 500 characters")]
    public string Value { get; set; }

    [StringLength(500, ErrorMessage = "Display name can not be longer than 500 characters")]
    public string DisplayName { get; set; } 
}

As you can see there is not Required attribute for the DisplayName field, but whenever I pass a null value from VueJS app for this field I get The DisplayName field is required..

I am trying to figure out why would AspNet Core complain for this, since there is no Required attribute for such field!

Does anybody know if this intentional ? I tried to remove the StringLength attribute and still it triggers required attribute.

My action is fairly simple:

[HttpPost(UrlPath + "addConfigurationContextValue")]
public async Task AddConfigurationContextValue([FromBody]AddConfigurationContextValueApiRequest request)
{
    using var unitOfWork = _unitOfWorkProvider.GetOrCreate();
    if (!ModelState.IsValid)
    {
        //Here it throws because ModelState is invalid
        throw new BadRequestException(ModelState.GetErrors());
    }

    //do stuff

    await unitOfWork.CommitAndCheckAsync();
}

Solution

  • After @devNull's suggestion I found out that somehow while I was playing around with Rider IDE it seems it switched that feature on!

    There is an option in rider that allows to change that configuration on project level:

    If somebody has the same problem: right click on the project level, go to properties, Application and there you can see this configuration.

    Thank you @devNull for the help :)

    enter image description here