I'm trying to make a route, but it's not working in this case:
If I call:
http://mysite.com/api/v1/product/Generic/1A
works fine.
If I call:
http://mysite.com/api/v1/product?=Generic
works too, but when I call:
http://mysite.com/api/v1/product/Generic
I get this error:
{
"Message":"The request is invalid.",
"MessageDetail":"The parameters dictionary contains a null entry for parameter 'type'
of non-nullable type 'GType' for method 'System.Net.Http.HttpResponseMessage
Get(GType)' in 'MySite.ControllersApi.V2.ProductController'. An optional parameter must
be a reference type, a nullable type, or be declared as an optional parameter."
}
The code of my route:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute
(
name: "DefaultApi",
routeTemplate: "api/{version}/{controller}/{type}/{id}",
defaults: new { id = RouteParameter.Optional, version = "v1", controller = "Product" }
)
}
}
public enum GType
{
Big,
Small,
Generic,
}
And the Controller:
public HttpResponseMessage Get(GType type)
{
...
}
public HttpResponseMessage Get(GType type, string id)
{
...
}
So, Web API isn't parsing the value in the URL. Did I forget anything?
Well, I still can't see how your first url actually works, but the issue with the second url is that you are trying to pass an invalid bit of data as a parameter.
To keep it simple, I'm just going to pretend for a minute that your route definition is this:
routeTemplate: "api/{controller}/{type}/{id}",
defaults: new { id = RouteParameter.Optional }
If you were to call a GET on this url http://mysite.com/product/Generic
, then you will get the same error you are running into. This url will resolve a controller of ProductController , with a parameter called type that will have a value of Generic .
However, your type
parameter has an actual Type of GType
, which is an enum. Generic is not a valid value for that so an error occurs. It's the same as sending "abcd" as the value for a parameter that is an int
.
If you tried to call a get to http://mysite.com/product/Big
, it would work, as it would be able to parse that value (Big) and a member of the GType
enum.
The problem was that I have two equals routes, but with diferents parameters name.
api/{version}/{controller}/{type}/{id}
and
api/{version}/{controller}/{id}
The second must be the last route declared.
The route you show us doesn't remotely match the URLs you're trying to hit. I have a feeling you're looking at the wrong route. Also, shouldn't "/Product/"
be " /{controller}/"
?
Oh, and you mis-spelled routeTamplate
[sic] in the snippet. I assume that was a transcription error -- I'm pretty sure the compiler would bark on that.
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.