Search code examples
asp.net-mvcasp.net-mvc-3asp.net-mvc-4asp.net-web-apifiddler

How to call web api with data


In my web api controller i have two functions with following structure

public HttpResponseMessage Post(CountryDto country)
 {
    var countries = _countryAppService.RegisterNewCountry(country);
    var message = Request.CreateResponse(HttpStatusCode.Created, countries);
    return message;
 }

public HttpResponseMessage Post(int countryId, StateDto state)
{
    var country = _countryAppService.AddNewState(state, countryId);
    var message = Request.CreateResponse(HttpStatusCode.Created, country);
    return message;
}

I need to call the second overloaded version of post , i tried this using fiddler with following http request details

POST http://localhost:51830/api/Country/ HTTP/1.1
User-Agent: Fiddler
Host: localhost:51830
Content-Type: application/json; charset=utf-8
Content-Length: 63

{"countryId":5,"state":{"StateName":"Dallas","StateCode":"DA"}}

but its calling the first overloaded post instead of second post, what i am missing and how i can call the second post using fiddler


Solution

  • There's no support for overloading in WebAPI (nor in MVC).

    However you can use attribute-based routing to achieve what you want, i.e.:

    [Route("api/country/add")]
    public HttpResponseMessage AddCountry(CountryDto country)
    
    [Route("api/country/addstate")]
    public HttpResponseMessage AddCountry(int countryId, StateDto state)
    

    You need to make sure you call config.MapHttpAttributeRoutes(); before the rest of the routing in configuration(i.e.: config.Routes.MapHttpRoute...)