locked
Call Web API in MVC RRS feed

  • Question

  • User52625461 posted

    Hi All,

    Can anyone give me example how to call Web API from MVC when both are in same solution and in same project ?

    Thanks !

    Friday, September 26, 2014 6:17 AM

All replies

  • User197322208 posted

    Can anyone give me example how to call Web API from MVC when both are in same solution and in same project ?

    Put the code of WebApi in a class method. Call the class method from both WebApi and MVC

    Friday, September 26, 2014 6:25 AM
  • User-417640953 posted

    Hi rohitpundlik,

    Thanks for the post.

    From you I understand that you want to call the web api in the mvc with in the same project.

    Here I made a web api class like below:

     public class DefaultController : ApiController
        {
    
            // GET api/values
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    
    
        }

    And the route like below:

    public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }

    Then you can call this web api action using javascript (in mvc view) or WebClient (in mvc controller).

    # Using javascript like below:

    <script src="//code.jquery.com/jquery-1.10.2.js"></script> 
    <script>
        $(function () { 
            $.ajax({
    
                type: "GET",
                contentType: "application/json", 
                url: "../api/Default",
                data: "{}",
                dataType: 'Json',
                success: function (result) {
                    var data = eval(result);
                    alert(data); 
                } 
            });
    
        }) 
    </script>

    # Using WebClient like below (you can also try to use HttpWebRequest):

    public ActionResult Index()
            { 
                WebClient webClient = new WebClient();
                webClient.Headers["Accept"] = "application/json";
                string result= result= webClient.DownloadString("http://localhost:40418/api/Default");
                //your code............
    
    
                return View();
            }

    Thanks.

    Best Regards!

    Saturday, September 27, 2014 2:10 AM
  • User52625461 posted

    Ok, got it...

    But do i need to write two controllers each time one for web api and other for mvc ?

    Monday, September 29, 2014 1:02 AM
  • User503812343 posted

    you can call it from view  by making jQuery.Ajax call  or ASP.NET MVC controller.

    http://dotnetmentors.com/mvc/web-api-in-mvc-tutorial.aspx

    below is example of getting it using jQuery

     $(document).ready(function () {
            // Send an AJAX request
            var rows = '';
            $('#customers').empty();
    
            $.getJSON(apiCustomers,
                function (data) {
                    $.each(data, function (key, val) {
                        var customerURL = apiCustomers + '/' + val.CustomerID;
                        rows = rows + '<tr style="border: 1px solid black;"><td>  ' +
                        '<a style="color: Blue; font-weight:bold; font-size:15px"'
                           + 'href="' + customerURL + '">' + val.CustomerID + '</a>' +
                            '</td><td>' + val.CompanyName + 
                            '</td><td>' + val.City + '</td></tr>';
                    });
                    $('#customers').html(rows);
                });
        });

    Monday, September 29, 2014 6:26 AM
  • User-760709272 posted

    Ok, got it...

    But do i need to write two controllers each time one for web api and other for mvc ?

    Yes.  Interacting with your own project over webapi is pointless, you're just introducing performance bottle necks when you don't need to.  For intra-project communication just talk to classes directly rather than going via a web service api (of any kind, including MVC, ASMX Soap Service, WebApi etc etc)

    Monday, September 29, 2014 6:37 AM
  • User52625461 posted

    rohitpundlik

    Ok, got it...

    But do i need to write two controllers each time one for web api and other for mvc ?

    Yes.  Interacting with your own project over webapi is pointless, you're just introducing performance bottle necks when you don't need to.  For intra-project communication just talk to classes directly rather than going via a web service api (of any kind, including MVC, ASMX Soap Service, WebApi etc etc)

    Ok, thats fine...

    But we want to use the application on web as well as on mobile also, by keeping the same platform.

    We ONLY want to change the UI side only if we want to build the mobile application.

    So which will be the better approach in MVC ?

    Monday, September 29, 2014 7:21 AM
  • User-760709272 posted

    You can still expose an API that the mobile app will use, but I'd make that API call some shared code that the non-mobile site calls direct so that you still have one place for your code logic but different ways to access it.  Making your website use a web api just so you can have a mobile app too is a bit overkill.

    Monday, September 29, 2014 7:56 AM
  • User52625461 posted

    You can still expose an API that the mobile app will use, but I'd make that API call some shared code that the non-mobile site calls direct so that you still have one place for your code logic but different ways to access it.  

    Can you give any simple example ?

    Monday, September 29, 2014 8:38 AM
  • User-760709272 posted
    public class SomeLogic
    {
        public void DoSomething()
        {
            // your code goes here
        }
    }
    
    public class YourWebApiController
    {
        [WebMethod] // use whatever decoration is relevant to your implementation
        public void DoSomething()
        {
            SomeLogic logic = new SomeLogic();
            logic.DoSomething();
        }
    }
    
    public class SomeControllerOnYourWebsite
    {
        public ActionResult Index()
        {
            SomeLogic logic = new SomeLogic();
            logic.DoSomething();
            return View();        
        }
    }

    Monday, September 29, 2014 8:44 AM