Home > Back-end >  How to set default value in ASP.NET Core?
How to set default value in ASP.NET Core?

Time:06-30

I am learning ASP.NET Core Web API, and it's using the System.Text.Json namespace instead of JSON.NET.

How to set the default value for the model binding?

Someone tells me that the [DefaultValue] attribute is not working anymore, is that correct?

If so what's the alternative option?

CodePudding user response:

Below is a demo, you can refer to it.

Student

public class Student
    {
      public string name { get; set; }    
    }

ValuesController

    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        
        [HttpGet]
        public string Get(string name="Tom")
        {
            return $"Hello {name}!";
        }
     }

Result:

enter image description here

CodePudding user response:

with latest c# you can do this.

public class Student
{
  public string name { get; set; } = "YourDefaultValue"
} 
   

then you can use System.text.json to serialize. check below example.

enter image description here

  • Related