Web API Validation and Default Values

This is the spiritual successor to my previous question Routing and Validation of Web Interface API Attributes - Possible? which, I think, was too general to answer. Most of these issues have been resolved, but the default question remains.

Basically, I solved many pieces of the puzzle. I have it:

[HttpGet]
[Route("test/{id}"]
public IHttpActionResult RunTest([FromUri]TestRequest request)
{
    if (!ModelState.IsValid) return BadRequest(ModelState);
    return Ok();
}

My TestRequestclass:

public class TestRequest
{
    public string id { get; set; }

    [DefaultValue("SomethingDefault")]
    public string something { get; set; }
}

The problem is that if somethingthere is no parameter in the query string for , the model is "real", but somethingequal null.

If I specify an empty value for something(i.e. GET test/123?something=) then the default value will come into play and the model will return again.

? ? , , , , , ?

( ASP.NET . - , DefaultValueAttribute , null, )

+5
2

:

public class TestRequest
{
    public TestRequest()
    {
        this.something = "SomethingDefault";
    }

    public string id { get; set; }

    [DefaultValue("SomethingDefault")]
    public string something { get; set; }
}

:
# 6 . :

public class TestRequest
{
    public string id { get; set; }

    [DefaultValue("SomethingDefault")]
    public string something { get; set; } = "SomethingDefault";
}

DefaultValueAttribute :

DefaultValueAttribute . .

, " something, , ModelBinder , , , , .

+5

, , , null.

, [DefaultValue("")] - , . , .

, PreserveBlankStringAttribute, DefaultValueAttribute, [DefaultValue("")].

, , .

+4

All Articles