3
votes

Anyone know how to remedy this error?

Specified cast is not valid.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Specified cast is not valid.

Here is the line of code where it breaks -

var id = (int)httpContext.Request.RequestContext.RouteData.Values["id"];
3

3 Answers

5
votes

httpContext.Request.RequestContext.RouteData.Values["id"] is probably a string, therefore you need to parse it:

var idStr=(string)(httpContext.Request.RequestContext.RouteData.Values["id"]);
int id;
if(int.TryParse(idStr, out id))
{
    //w00t
}
1
votes

Your value, httpContext.Request.RequestContext.RouteData.Values["id"] probably doesn't have an int equivalent.

if it's a string, as spender said, you would try,

var id = int.Parse("httpContext.Request.RequestContext.RouteData.Values["id"]);

intellisence might tell you what type:

httpContext.Request.RequestContext.RouteData.Values["id"]

is as you type it. You can also find out in the "watch" tab of your debugger

0
votes

first call ToString()

then parse it to int

int.Parse(Url.RequestContext.RouteData.Values["id"].ToString())