简体   繁体   中英

Asp.Net WebApi model binding nullable datetime

Hello,

I have api GET-method /rating (ASP.Net WebApi 2.1), which accepts objects of type ChartPageRequest :

// comments're removed for readability
public sealed class ChartPageRequest
{
    public DateTime? From { get; set; }

    public DateTime? To { get; set; }

    public string Cursor { get; set; }

    [Range(-100, 100)]
    public int Take { get; set; } = 10;
}

/rating method has following signature:

[HttpGet]
[Route("rating")]
[ResponseType(typeof(ChartPage))]
[ValidateModelState]
public async Task<IHttpActionResult> GetTranslationRatingChartAsync([ModelBinder] ChartPageRequest model)
{
    // body here
}

And ValidateModelState attribute is just a custom attribute which returns custom response when ModelState isn't valid. It doesn't check anything by itself except HttpActionContext.ModelState.IsValid property.

This api method works fine except one case - when client explicitly passes null value to DateTime? properties of ChartPageRequest , eg:

/rating?from=2016-07-08 12:01:55.604&to=null

In this case ValidateModelState attribute registers invalid ModelState with following message: The value 'null' is not valid for To .

I've found this kind of problem quite popular, but haven't found any good workarounds without creating custom model binder. So here's the questions:

  1. Is there another approach without custom model binder?

  2. In case there isn't, how can I take only "accepting null" job and leave DateTime parsing to default binder in my custom binder?

  3. Do I need to accept those nulls at all? All clients are developing by my colleagues so I can force them to not send it. Is it good practice after all?

Thanks!

I didn't validate this method, but I guess you can try parse it yourself, though I think it's not a convenient way, first use a string to get the To :

public string To { get; set; }

And give another property DateTimeTo and parse To yourself:

public DateTime? DateTimeTo { get; set; }

public void ParseTo()
{
    if(To.ToLower() == "null")
        DateTimeTo = null;
    else
        DateTimeTo = Convert.ToDateTime(To); 
}

And DateTimeTo is the parsed result property.

I recently ran into some Asp.Net WebApi parsing body issue, the parsing doesn't work very well in some condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM