跨越问题主要发生在客户端ajax请求时,为了安全设置,默认webapi是不允许ajax跨越请求的,不过有方法设置让支持跨越,我说说最常见的两种方法

一、jquery jsonp

缺点:JSONP也有局限性,只能针对于Get请求不能用于POST请求

1、新建过滤器

Filters/JsonCallbackAttribute.cs

using System.Net.Http;
using System.Text;
using System.Web.Http.Filters; namespace cms.Web
{
public class JsonCallbackAttribute : ActionFilterAttribute
{
private const string CallbackQueryParameter = "jsoncallback"; public override void OnActionExecuted(HttpActionExecutedContext context)
{
var callback = string.Empty; if (IsJsonp(out callback))
{
var jsonBuilder = new StringBuilder(callback); jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result); context.Response.Content = new StringContent(jsonBuilder.ToString());
} base.OnActionExecuted(context);
} private bool IsJsonp(out string callback)
{
callback = System.Web.HttpContext.Current.Request.QueryString[CallbackQueryParameter]; return !string.IsNullOrEmpty(callback);
}
}
}

2、Global.asax注册

protected void Application_Start()
{
GlobalConfiguration.Configuration.Filters.Add(new JsonCallbackAttribute());//让webapi支持jsonp跨越请求
}

3、webapi

api方法地址:www.ceshi1.com/api/ceshi/getceshi

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Results;
using cms.BLL;
using cms.Model; namespace cms.Web.API
{
public class CeshiController : ApiController
{
public IHttpActionResult GetCeshi()
{
dynamic data = new { status = true, message = "webapi success" };
return Json<dynamic>(data);
}
}
}

4、ceshi.html

访问地址:www.ceshi2.com/ceshi.html

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ceshi3.aspx.cs" Inherits="ceshi3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="/js/jquery.js"></script>
</head>
<body>
测试结果1:<span id="test" style="color:Red"></span><br />
测试结果2:<span id="test2" style="color:Red"></span>
<script type="text/javascript">
function success_jsonpCallback(data) {
alert(data)
}
$(function () {
$.getJSON("http://www.ceshi1.com/api/ceshi/Getceshi?jsoncallback=?",
function (data) {
$("#test").html(data.message);
}
);
$.ajax({
type: "get",
url: "http://www.ceshi1.com/api/ceshi/Getceshi",
dataType: "jsonp",
jsonp: "jsoncallback",
//async: false,
success: function (data) {
$("#test2").html(data.message);
},
error: function (e) {
$("#test2").html("Error");
}
}); });
</script>
</body>
</html>

二、webapi.cors

CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。
它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

推荐使用这个解决跨越问题

1、安装webapi.cors

2、配置WebApiConfig

using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Cors; namespace WebApi
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务 //设置cors允许跨越
config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

3、webapi

api方法地址:www.ceshi1.com/api/ceshi/getceshi

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http; namespace WebApi.Controllers
{
//自定义cors
//[EnableCors(origins: "http://www.ceshi2.com", headers: "*", methods: "*")]
//[EnableCors(origins: "http://www.example.com", headers: "*", methods: "get,post")]
public class CeshiController : ApiController
{
public IHttpActionResult GetCeshi()
{
dynamic data = new { status = true, message = "webapi success" };
return Json<dynamic>(data);
}
}
}

4、ceshi.html

访问地址:www.ceshi2.com/ceshi.html

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ceshi3.aspx.cs" Inherits="ceshi3" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="/js/jquery.js"></script>
</head>
<body>
测试结果1:<span id="test" style="color:Red"></span><br />
测试结果2:<span id="test2" style="color:Red"></span>
<script type="text/javascript">
$(function () {
$.get("http://1.ceshi.com/api/ceshi/Getceshi",
function (data) {
$("#test").html(data.message);
}
);
jQuery.support.cors = true;//必须,不然ie8、ie9不支持跨越
$.ajax({
type: "get",
url: "http://1.ceshi.com/api/ceshi/Getceshi",
//dataType: "json",
success: function (data) {
$("#test2").html(data.message);
},
error: function (e) {
$("#test2").html("Error");
}
}); });
</script>
</body>
</html>

说明:cors设置后ajax就和普通写法一样调用了

注意:刚开始我的webapi和mvc在一个项目中,设置cors不起作用,不知道为何。然后把webapi单独一个项目却可以,坑死我了。

end

Asp.Net WebApi 跨域设置的更多相关文章

  1. C# ASP.NET WebApi 跨域设置

    概述 前后端分离开发模式,一定会遇到跨域的问题.这里收集了2种 C# Asp.Net webapi 相关的跨域解决方案,方便后续查找参考. 2021/10/28 更新: 有更加简单高效的方式推荐< ...

  2. 连表查询都用Left Join吧 以Windows服务方式运行.NET Core程序 HTTP和HTTPS的区别 ASP.NET SignalR介绍 asp.net—WebApi跨域 asp.net—自定义轻量级ORM C#之23中设计模式

    连表查询都用Left Join吧   最近看同事的代码,SQL连表查询的时候很多时候用的是Inner Join,而我觉得对我们的业务而言,99.9%都应该使用Left Join(还有0.1%我不知道在 ...

  3. asp.net—WebApi跨域

    一.什么是跨域? 定义:是指浏览器不能执行其他网站的脚本,它是由浏览器的同源策略造成的,是浏览器对JavaScript实施的安全限制. 同源策略限制了以下行为: 1.Cookie.LocalStora ...

  4. Asp.net core 跨域设置

    验证环境: dotnet core 2.1/Asp.net core2.1 一.作用域在中间件层  配置的方式是在startup.cs文件Configure(IApplicationBuilder a ...

  5. 【天坑】ASP.net WebAPI跨域调用问题

    最近在做一个项目,前端是VUE,后端是WebAPI,业务也就是一些实体的增删改查.在项目开始的时候我就预计到有跨域的问题,所以也找了一下资料,在Web.Config里面加上了配置信息: <htt ...

  6. ASP.NET WEBAPI 跨域请求 405错误

    浏览器报错 本来没有报这个错,当我在ajax中添加了请求头信息时报错 405的报错大概就是后端程序没有允许此次请求,要解决这个问题,就是在后端程序中允许请求通过.具体操作就是修改web.config配 ...

  7. C# ASP.NET MVC/WebApi 或者 ASP.NET CORE 最简单高效的跨域设置

    概述 前面写了一篇:<C# ASP.NET WebApi 跨域设置>的文章,主要针对 ASP.NET WebApi 项目. 今天遇到 ASP.NET MVC 项目也需要设置跨域,否则浏览器 ...

  8. ASP.NET WebAPI2复杂请求跨域设置

    ASP.Net Core的跨域设置比较简单  官方都整合了 具体的参见微软官方文档: https://docs.microsoft.com/zh-cn/aspnet/core/security/cor ...

  9. WebApi服务以及跨域设置

    WCF 它利用TCP.HTTP.MSMQ等传输协议构建“契约先行”的服务.WCF最初为基于SOAP的服务而设计[xml],繁琐.冗余.慢.沉重 WebApi 基于http协议,轻量级的,支持URL路由 ...

随机推荐

  1. 给有C或C++基础的Python入门 :Python Crash Course 4 操作列表 4.1--4.3

    操作列表,也就是遍历列表.本章我们要学的就是如何遍历列表. 4.1--4.2 遍历列表 遍历列表,用for循环. 不同于C++或者C语言的for循环,Python的for循环更容易让人理解. 看一个例 ...

  2. 洛谷P2569 股票交易

    题目传送门https://www.luogu.org/problemnew/show/P2569 第一眼看题就觉得是个dp ,然后看到2000的范围,hmm大概是个n^2的2维dp 开始设状态,第一维 ...

  3. Python2048小游戏demo

    # -*- coding:UTF-8 -*- #! /usr/bin/python3 import random v = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, ...

  4. No compiler is provided in this environment.Perhaps you are running on a JRE rather than a JDK?报错解决

    Maven install 时出现如上错误. Eclipse-->Window-->preferences-->Java-->Installed JREs 查看jdk: 发现此 ...

  5. curl获取结果乱码的解决方法之CURLOPT_ENCODING(curl/Post请求)

    //php脚本开始   /*POST请求远程内容函数*/   function ppost($url,$data,$ref){ // 模拟提交数据函数       $curl = curl_init( ...

  6. [CC-CLPOINT]Optimal Point

    [CC-CLPOINT]Optimal Point 题目大意: 在\(k(k\le5)\)维空间中,如果点\(X\)的坐标为\((x_1,x_2,\ldots,x_k)\),点\(Y\)的坐标为\(( ...

  7. js 创建Table,每行3列的方式

    table: <table style="width:100%" id="appDatas"></table> 1. var table ...

  8. 【分块】教主的魔法 @洛谷P2801/upcexam3138

    时间限制: 1 Sec 内存限制: 128 MB 题目描述 教主最近学会了一种神奇的魔法,能够使人长高.于是他准备演示给XMYZ信息组每个英雄看.于是N个英雄们又一次聚集在了一起,这次他们排成了一列, ...

  9. js+css3+HTML5拖动滑块(type="range")改变值

    最近在做一个H5的改版项目,产品和设计给出的效果中有一个拖动滑块可以改变输入值的效果,类似如下图这样: 拿到这样的设计稿后,我有点懵了,自己写一个js?去网上找一个这样的效果?自己写一个可以,只是实现 ...

  10. py3 pymysql

    虽然大家可能在python2.x中用习惯了mysqldb,但是在python3.x中已经不支持那个组件了. 取而代之的是: import pymysql 所以,大家pip起来吧.另外,mysql官方出 ...