webapi项目下html访问,c# – 如何在MVC4项目中调用/引用外部web api项目

我是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 GetStudents()

{

RegisterStudent_API_DB objRegisterStudent = new RegisterStudent_API_DB();

List 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 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项目?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值