Michael
Michael

Reputation: 13616

Why get error 404 when I try to pass date variable in get request to web api method?

I work on my web api project. I get error 404 when I try to pass date variable in get request to web api method.

Here is web api method:

[HttpGet]
[Route("ReportDetailed/{clientId}/{date}")]
public IHttpActionResult ReportDetailed(int clientId, DateTime date )
{
    return Ok();
}

And here how I try to access to the function above(row from URL):

http://localhost/station/api/Reports/ReportDetailed/12/Wed%20Jun%2001%202016%2000:00:00%20GMT+0300%20(Jerusalem%20Daylight%20Time)

where clientId is 12 and date is parsed javascript date object:

/Wed%20Jun%2001%202016%2000:00:00%20GMT+0300%20(Jerusalem%20Daylight%20Time)

when I remove from URL above the parsed Date object and date parameter from web api function it works perfect (so I guess the problem with date object).

Any idea why I get error 404 when I try to pass object in URI?

Upvotes: 0

Views: 1079

Answers (2)

Nkosi
Nkosi

Reputation: 247018

Your provided date is not in a valid date format. Try a more universally parse-able format like YYYY-MM-dd HH:mm:ss for example.

You should also use Route constraints on your parameters which will try to validate your parameters to make sure they are in the correct format

[HttpGet]
[Route("ReportDetailed/{clientId:int}/{date:datetime}")]
public IHttpActionResult ReportDetailed(int clientId, DateTime date )
{
    return Ok();
}

Upvotes: 1

Anonymous Duck
Anonymous Duck

Reputation: 2978

Date format is not recognizable by .NET First convert your date to UTC string, this will return a string representation of your date. So the value will be passes as string

var dateString= dateJs.toUTCString();

Then in your C# code parse it.

public IHttpActionResult ReportDetailed(int clientId, string dateString)
    DateTime dateC# = DateTime.Parse(dateString);

Upvotes: 1

Related Questions