Quantcast
Channel: amitpatelit » .NET
Viewing all articles
Browse latest Browse all 11

Use MVC Web API

$
0
0

Visual studio 2012 provides a features of the asp.net MVC with web api with web services to rest service call.

So when need to create web services we can use this one rather than creating a traditional web services or WCF services.

Below are the process for this to create MVC web api.

  • Select Project with asp.net MVC
  • Select Web API Template
  • Web API Template

    Web API Template

  • Then project created with web api template and one default values controller created.
  • In this control you have web method available so we can use this method as web services as rest services.
  • Below are the code.

    {
            // GET api/values
            public IEnumerable<string> GetData()
            {
                return new string[] { "value1", "value2" };
            }
    }
    

    So once call below url

    http://localhost/API/Values

    It execute GetData and if post request via Post method then it execute Post method. Here we don’t need to set action method.
    If need to use different action method then make below changes in WebApiConfig

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

    Change below with action method so we can use different action methods

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

    Thanks,
    Amit Patel
    “Enjoy Programming”



    Viewing all articles
    Browse latest Browse all 11

    Trending Articles