Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webapi method Get with string parameter not getting invoked

I am creating asp.net webapi with two get methods. One returns all the records while the other should be filtering based on a string parameter called countrycode. I am not sure for what reason the get method with string parameter doesnt get invoked.

I tried the following uri's

http://localhost:64389/api/team/'GB'
http://localhost:64389/api/team/GB

Following is my code

Web API

public HttpResponseMessage Get()
        {
            var teams = _teamServices.GetTeam();
            if (teams != null)
            {
                var teamEntities = teams as List<TeamDto> ?? teams.ToList();
                if (teamEntities.Any())
                    return Request.CreateResponse(HttpStatusCode.OK, teamEntities);
            }
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Team not found");

        }

        public HttpResponseMessage Get(string countryCode)
        {
            if (countryCode != null)
            {

                var team = _teamServices.GetTeamById(countryCode);
                if (team != null)
                    return Request.CreateResponse(HttpStatusCode.OK, team);
            }

            throw new Exception();
        }

WebAPIConfig

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Formatters.JsonFormatter.SupportedMediaTypes
            .Add(new MediaTypeHeaderValue("text/html"));
        }
    }
like image 349
Tom Avatar asked Mar 13 '17 11:03

Tom


People also ask

Can we pass object as a parameter to Web API GET method?

Web API provides the necessary action methods for HTTP GET, POST, PUT, and DELETE operations. You would typically pass a single object as a parameter to the PUT and POST action methods. Note that Web API does not support passing multiple POST parameters to Web API controller methods by default.

What is difference between FromQuery and FromBody?

[FromQuery] - Gets values from the query string. [FromRoute] - Gets values from route data. [FromForm] - Gets values from posted form fields. [FromBody] - Gets values from the request body.

Can we use FromBody with HttpGet?

A Get does not send the body of the form, it only requests a URL. Use a <form> in your view and post it to your controller method, which needs to be decorated with HttpPost.


1 Answers

I think you are probably hitting the default 'Get()' method from your default API route.
I expect if you changed the parameter name to 'id' on your method like so, it would also work:

public HttpResponseMessage Get(string id)

This is because the optional parameter name in the default route is 'id'.

For attribute routing to work, you need to decorate your controller and methods with the values which were previously inferred by the route configuration.
So at the top of your controller, you would probably have:

[RoutePrefix("api/team")]
public class TeamController : ApiController

Then above your second get method:

[Route("{countryCode}")]
public HttpResponseMessage Get(string countryCode)

Since attribute routing, I haven't used the "old-style" routing.
Check out the ASP.NET page on attribute routing for more information.

Edit for comment:
If you have two routes which have the same parameters you need to differentiate them somehow in the route. So for your example of get by team name, I would probably do something like this:

[HttpGet()]
[Route("byTeamName/{teamName}")]
public HttpResponseMessage GetByTeamName(string teamName)

Your url would then be /api/team/byTeamName/...

Your other method name is "Get" and the default HTTP attribute routing looks for method names with the same as HTTP verbs. However you can name your methods anything you like and decorate them with the verbs instead.

like image 99
Craig H Avatar answered Oct 20 '22 00:10

Craig H