How to call a method in ApiController with http request?

20,666

So you have incorrect controller name (it should ends with *Controller) and wrong routes. Try renaming your controller to ServiceController and update your routes like that:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{priceId}/{cost}/{lastUpdate}",
    defaults: new { controller = "service", action="updateprice", priceId = RouteParameter.Optional, cost = RouteParameter.Optional, lastUpdate = RouteParameter.Optional}
);

And format your URL like that:

string serviceUrl = string.Format("http://localhost:26769/api/service/updateprice/{0}/{1}/{2}", priceId, cost, DateTime.Now);
    WebRequest request = WebRequest.Create(serviceUrl);
    WebResponse response = request.GetResponse();

And add [HttpGet] attribute on your UpdatePrice action:

public class Service : ApiController
{
    PriceApplication priceApp = new PriceApplication();
    [HttpGet]
    public int UpdatePrice(int priceId,int cost,DateTime lastUpdate)
    {
        try
        {
            var price = priceApp.GetByPriceId(priceId);
            price.Cost = Convert.ToDecimal(cost);
            price.LastUpdate = lastUpdate;
            priceApp.Update(price);
            return cost;
        }
        catch
        {
            return -1;
        }
    }
}
Share:
20,666

Related videos on Youtube

Hamid Reza
Author by

Hamid Reza

Updated on July 17, 2022

Comments

  • Hamid Reza
    Hamid Reza over 1 year

    I have an ApiController named Service. I have a method named UpdatePrice in it. Now I want to send a http web request from another project to it by I receive 404 error code. And if I run it in browser I see this:

    <Error>
        <Message>No HTTP resource was found that matches the request URI 'http://localhost:26769/api/service/updateprice?priceId=16&cost=1234&lastUpdate=2014-10-15 11:41:54.000'.</Message>
        <MessageDetail>No type was found that matches the controller named 'service'.</MessageDetail>
    </Error>
    

    This is the ApiController:

    public class Service : ApiController
    {
        PriceApplication priceApp = new PriceApplication();
        public int UpdatePrice(int priceId,int cost,DateTime lastUpdate)
        {
            try
            {
                var price = priceApp.GetByPriceId(priceId);
                price.Cost = Convert.ToDecimal(cost);
                price.LastUpdate = lastUpdate;
                priceApp.Update(price);
                return cost;
            }
            catch
            {
                return -1;
            }
        }
    }
    

    This is the routing for it:

    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { controller = "service",action="updateprice", id = RouteParameter.Optional}
    );
    

    And this is the request:

    string serviceUrl = string.Format("http://localhost:26769/api/service/updateprice?priceId={0}&cost={1}&lastUpdate={2}", priceId, cost, DateTime.Now);
    WebRequest request = WebRequest.Create(serviceUrl);
    WebResponse response = request.GetResponse();
    
    • Ben Robinson
      Ben Robinson about 9 years
      Rename your controller ServiceController. You may also want to consider attribute routing. asp.net/web-api/overview/web-api-routing-and-actions/…
    • Trevor Pilley
      Trevor Pilley about 9 years
      @HamidReza - the object you pass to the API does not have to be the model itself, you could create an public class PriceUpdate { public int PriceId {get;set;} public decimal Cost{get;set;}} which you POST to the controller and then load the record and update it based upon those values. The problem with doing a GET is that a read request can change the data which is not expected behaviour
  • Hamid Reza
    Hamid Reza about 9 years
    I received 500 Bad Request error and the I removed the lastUpdate property from the query string and routing and now I get this error: The remote server returned an error: (405) Method Not Allowed.
  • Vladimirs
    Vladimirs about 9 years
    @HamidReza 500 error related to wrong datetime format. Try ISO formatting or dd-MM-yyyy (can't remember which used in datetime model binder). For 405 also not quite clear you kinda have Get on your action and sending Get request.. Maybe try decorate your action with HttpGet or try accessing that link from browser to see what the difference is.
  • Sandip Subedi
    Sandip Subedi over 6 years
    @Vladimirs is the use of [HttpGet] required or it's just a general convention ?
  • Vladimirs
    Vladimirs over 6 years
    @SandipSubedi it is required, otherwise it will be defaulted to POST (unless verb can be resolved from action name e.g. if it starts with Get, Put, Delete and etc, like PutComment).
  • Sandip Subedi
    Sandip Subedi over 6 years
    Thank you so much. I saw it many places and didn't know if that was something required or a general convention.

Related