MVC+EF API 跨域
一、 MVC+EF
不管是MvcHAIS Ef 都有文件夹Controller
二、Link查询
-
多表联查
-
匿名类型
三、Postman使用
四、mvc访问使用API
-
跨域设置:(直接复制粘贴)
-
跨域请求(在UI层的Web.config 中<system.webServer>中的 </handlers> 下面)
-
<!--跨域请求:三个配置信息-->
<httpProtocol>
<customHeaders>
<!--响应类型 (值为逗号分隔的一个字符串,表明服务器支持的所有跨域请求的方法)-->
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS"/>
<!--响应头设置(Content-Type:只限于三个值application/x-www-form-urlencoded、multipart/form-data、text/plain)-->
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<!--如果设置 Access-Control-Allow-Origin:*,则允许所有域名的脚本访问该资源-->
<add name="Access-Control-Allow-Origin" value="*" />
<!--<add name="Access-Control-Allow-Origin" value="http://domain1.com, http://domain2.com" /> 设置允许跨域访问的网址-->
</customHeaders>
</httpProtocol>
-
跨域设置(UI层的Global.asax 中 直接粘贴到原本方法下面)
-
/// <summary>
/// 跨域设置
/// </summary>
protected void Application_BeginRequest()
{
//OPTIONS请求方法的主要作用:
//1、获取服务器支持的HTTP请求方法;也是黑客经常使用的方法。
//2、用来检查服务器的性能。如:AJAX进行跨域请求时的预检,需要向另外一个域名的资源发送一个HTTP OPTIONS请求头,用以判断实际发送的请求是否安全。
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
//表示对输出的内容进行缓冲,执行page.Response.Flush()时,会等所有内容缓冲完毕,将内容发送到客户端。
//这样就不会出错,造成页面卡死状态,让用户无限制的等下去
Response.Flush();
}
} -
在MVC中
-
用ajax显示分页查询
-
<input type="text" id="SName" />
<select id="nclass">
<option>请选择</option>
</select>
<input type="button" value="查询" onclick="Show()" />
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>学生姓名</td>
<td>班级</td>
</tr>
</thead>
<tbody id="tbd">
</tbody>
</table>
<a href="#" onclick="Page('F')">首页</a>
<a href="#" onclick="Page('N')">下页</a>
<a href="#" onclick="Page('P')">上页</a>
<a href="#" onclick="Page('L')">尾页</a>
<script>
var pageindex = 1;
var pagesize = 3;
var totalcount = 0;
var totalpage = 0;
var NId = "";
var SName = "";
$(function () {
Show();
nclass();
})
function Show() {
$.get('http://localhost:59125/api/Student/Show?NId=' + NId + '&SName=' + SName + '&pageindex=' + pageindex + '&pagesize=' + pagesize + '', res => {
//给总页数和总条数赋值
totalcount = res.totalcount;
totalpage = res.totalpage;
SName = $("#SName").val();
NId = $("#nclass").val();
$("#tbd").empty();
$(res.list).each(function () {
$("#tbd").append('<tr>' +
'<td>' + this.Id + '</td>' +
'<td>' + this.SName + '</td>' +
'<td>' + this.NName + '</td>' +
+'</tr>');
});
});
}
//分页
function Page(o) {
switch (o) {
case 'F':
pageindex = 1;
break;
case 'P':
pageindex = pageindex <= 1 ? pageindex : pageindex - 1;
break;
case 'N':
pageindex = pageindex >= totalpage ? pageindex : pageindex + 1;
break;
case 'L':
pageindex = totalcount;
break;
}
Show();
}
//下拉框
function nclass() {
$.get('http://localhost:59125/api/Student/nclass', res => {
$(res).each(function () {
$("#nclass").append(
'<option value="' + this.NId + '">' + this.NName + '</option>'
)
})
});
}
</script>
RESTful风格编写接口
Cors跨域

浙公网安备 33010602011771号