简体   繁体   中英

How to call/reference external web api project in MVC4 project


I am new to Web API & MVC
I have created new WEB API & MVC solution separately now i want to refer Web API action method in MVC so for that following code i written,
Web Api Project Side,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Data;
using System.Net.Http;
using System.Web.Http;
using AttributeRouting.Web.Mvc;
using RegisterStudent_WebAPI.Models;

    namespace Register_Student_WebAPI.Controllers 
    {
        public class RegisterStudentController : ApiController
        {
            [Route("api/student")]
            [HttpGet]
            public IEnumerable<Student> GetStudents()
            {
                RegisterStudent_API_DB objRegisterStudent = new RegisterStudent_API_DB();
                List<Student> lstStudent = objRegisterStudent.GetStudent();
                return lstStudent ;
            }
        } }

WEB.Config File from API,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;


namespace RegisterStudent_WebAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {


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

            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            config.EnableSystemDiagnosticsTracing();


            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
        }
    }
}


in MVC Project i have written following code in script tag(on load form) to refer WEB API Service,

$(document).ready(function () {   
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://localhost:18715/api/student',
            type: 'GET',
            dataType: 'json',
            success: function (data) {
                alert('success');
            },
            error: function (x) {
                alert(x.status);
            }
        });
    });

If i add reference of Web API project to MVC project then it's working fine but one of my friend told services should not be referred like that, Please guide me how to refer/include the hosted/cross domain running web api project to my MVC Project?

What you have done is not bad(at least - it is not forbidden ;)) but by referencing WebAPI directly in a MVC project you are binding it to the one, specific application, what will prevent you from reusing API in other projects/services.

In my opinion, WebAPI project should be hosted as another application(it is up to you whether it should be a self-hosted OWIN application/webservice/simple API application), what gives you some benefits:

  • it is separated from your MVC application logic
  • it can be deployed separately
  • it can be used by other applications/services
  • it is easier to maintain

Think of WebAPI as a RESTful webservice, an API which can be used by your applications or third-party applications.

To be honest using WebAPI directly in MVC just to feed your views some data seems like a little waste. What you are doing can be done thanks to JsonResult actions in your MVC controller. It is not ideal, but prevents you from creating another API project.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM