WebApi 500 Server Internal Error

I am experimenting with WebApi and created a controller with two methods.

First, I started with the following method:

[HttpGet] [Route("car/{registration}")] public object GetCarByRegistration(string registration) { return null; } 

When debugging, I set a breakpoint on return null; checked url http://localhost:51245/api/car/yw25jdk , which works fine, visual studio stopped at my breakpoint, and the registration variable was the same value in the url.

But when I added the following method:

  [HttpGet] [Route("car/{serial}")] public object GetCarBySerial(string serial) { return null; } 

The first URL stops working and I started getting 500 - Internal Server Error . If I take the second method, the first method works again.

I do not understand why the second method breaks the first.

Can someone please explain this to me?

+4
source share
2 answers

Good, because ASP does not know which method to use when you go to the url http http://localhost:51245/api/car/yw25jdk , since both methods say that they expect a string as their parameter.

How should ASP know the difference between /car/{registration} and /car/{serial] since both are strings?

You must change the enable route to make it work.

+7
source

Put this in your WebApiConfig:

  config.MapHttpAttributeRoutes(); 

Otherwise, WebApi ignores the Route attribute. And without different route signatures, when ApiController receives a GET request, it automatically searches for the first action that starts with β€œGet” - that’s why it works when you delete the second method

0
source

All Articles