[英]How to call/reference external web api project in MVC4 project
我是Web API和MVC的新手
我已經單獨創建了新的WEB API和MVC解決方案,現在我想在MVC中引用Web API動作方法,以便我編寫下面的代碼,
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 ;
}
} }
來自API的WEB.Config文件,
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"));
}
}
}
在MVC項目中我已經在腳本標簽(在加載表單上)編寫了以下代碼來引用WEB API服務,
$(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);
}
});
});
如果我將Web API項目的引用添加到MVC項目然后它工作正常但我的一個朋友告訴服務不應該被這樣引用,請指導我如何引用/包含運行web api項目的托管/跨域項目到我的MVC項目?
你所做的一切都不錯(至少 - 它不被禁止;))但是通過直接在MVC項目中引用WebAPI,你將它綁定到一個特定的應用程序,什么將阻止你在其他項目/服務中重用API 。
在我看來,WebAPI項目應該作為另一個應用程序托管(它取決於你是否應該是一個自托管的OWIN應用程序/ webservice / simple API應用程序),它給你一些好處:
將WebAPI視為RESTful Web服務,可以由應用程序或第三方應用程序使用的API。
老實說,直接在MVC中使用WebAPI只是為了提供你的觀點,一些數據似乎有點浪費。 由於MVC控制器中的JsonResult
操作,您正在做的事情可以完成。 它並不理想,但會阻止您創建另一個API項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.