关于WebAPI跨域的问题,网上已经很多了,以下方案可以解决很多跨域问题,但是都不支持IE8、IE9浏览器,JSONP也只能支持Get请求

  1. 通过dll配置 Install-Package Microsoft.AspNet.WebApi.Cors
  2. 配置 Web.config

IE8,IE9跨域是通过XDomainRequest这个对象去实现,和XMLHttpRequest类似,可以参考下面文档

https://msdn.microsoft.com/zh-cn/library/dd573303(v=vs.85).aspx

使用jQuery.ajax的基础上,在jQuery下面再引用

https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest/blob/master/jQuery.XDomainRequest.js

这样IE8、IE9跨域成功了

        public Response<string> Post()
{
Response<string> rs = new Response<string>
{
head = new ResponseHeader { errcode = , errmessage = "post" },
data = "hello"
};
return rs;
}

这样IE8、IE9跨域失败了

        public Response<string> Post(Request<Message> request)
{
Response<string> rs = new Response<string>
{
head = new ResponseHeader { errcode = , errmessage = "post" },
data = request.data.content
};
return rs;
}

后来通过排查,有对象形参的WebAPI就会遇到反序列化问题,(IE8,IE9)转换为request对象的時候报错

试了很多次,前端帶不过來Content-Type,就想到了用參数传递到后端,也修改了jQuery.XDOmainRequest.js这个文件

 /*!
* jQuery-ajaxTransport-XDomainRequest - v1.0.4 - 2015-03-05
* https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
* Copyright (c) 2015 Jason Moon (@JSONMOON)
* Licensed MIT (/blob/master/LICENSE.txt)
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals.
factory(jQuery);
}
}(function ($) { // Only continue if we're on IE8/IE9 with jQuery 1.5+ (contains the ajaxTransport function)
if ($.support.cors || !$.ajaxTransport || !window.XDomainRequest) {
return $;
} var httpRegEx = /^(https?:)?\/\//i;
var getOrPostRegEx = /^get|post$/i;
var sameSchemeRegEx = new RegExp('^(\/\/|' + location.protocol + ')', 'i'); // ajaxTransport exists in jQuery 1.5+
$.ajaxTransport('* text html xml json', function (options, userOptions, jqXHR) { // Only continue if the request is: asynchronous, uses GET or POST method, has HTTP or HTTPS protocol, and has the same scheme as the calling page
if (!options.crossDomain || !options.async || !getOrPostRegEx.test(options.type) || !httpRegEx.test(options.url) || !sameSchemeRegEx.test(options.url)) {
return;
} var xdr = null; return {
send: function (headers, complete) {
var postData = '';
var userType = (userOptions.dataType || '').toLowerCase(); xdr = new XDomainRequest();
if (/^\d+$/.test(userOptions.timeout)) {
xdr.timeout = userOptions.timeout;
} xdr.ontimeout = function () {
complete(500, 'timeout');
}; xdr.onload = function () {
var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
var status = {
code: 200,
message: 'success'
};
var responses = {
text: xdr.responseText
};
try {
if (userType === 'html' || /text\/html/i.test(xdr.contentType)) {
responses.html = xdr.responseText;
} else if (userType === 'json' || (userType !== 'text' && /\/json/i.test(xdr.contentType))) {
try {
responses.json = $.parseJSON(xdr.responseText);
} catch (e) {
status.code = 500;
status.message = 'parseerror';
//throw 'Invalid JSON: ' + xdr.responseText;
}
} else if (userType === 'xml' || (userType !== 'text' && /\/xml/i.test(xdr.contentType))) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = false;
try {
doc.loadXML(xdr.responseText);
} catch (e) {
doc = undefined;
}
if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
status.code = 500;
status.message = 'parseerror';
throw 'Invalid XML: ' + xdr.responseText;
}
responses.xml = doc;
}
} catch (parseMessage) {
throw parseMessage;
} finally {
complete(status.code, status.message, responses, allResponseHeaders);
}
}; // set an empty handler for 'onprogress' so requests don't get aborted
xdr.onprogress = function () { };
xdr.onerror = function () {
complete(500, 'error', {
text: xdr.responseText
});
}; if (userOptions.data) {
postData = ($.type(userOptions.data) === 'string') ? userOptions.data : $.param(userOptions.data);
}
if (options.contentType && options.contentType.length > 0) {
if (options.url.indexOf('?') > -1) {
options.url = options.url + '&_contentType=' + options.contentType;
} else {
options.url = options.url + '?_contentType=' + options.contentType;
}
}
xdr.open(options.type, options.url);
xdr.send(postData);
},
abort: function () {
if (xdr) {
xdr.abort();
}
}
};
}); return $; }));

jQuery.XDomainRequest.js

加上消息处理就可以解决

 public class CrossDomainFixIEHandler : DelegatingHandler
{
protected override System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Options)
{
HttpResponseMessage response = request.CreateResponse<string>(HttpStatusCode.OK, null);
TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
if (request.Content.Headers.ContentType == null || string.IsNullOrWhiteSpace(request.Content.Headers.ContentType.MediaType))
{
string contentType = this.GetContentType(string.Concat(request.RequestUri.Query, "&"));
if (string.IsNullOrWhiteSpace(contentType))
{
contentType = "application/json";
}
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
}
return base.SendAsync(request, cancellationToken);
} /// <summary>
/// 獲取ContentType
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
private string GetContentType(string source)
{
if (string.IsNullOrWhiteSpace(source))
{
return string.Empty;
}
Regex regex = new Regex("[&?]_contentType=(?<contentType>(.*?))&", RegexOptions.IgnoreCase);
Match match = regex.Match(source);
if (match.Success)
{
return match.Groups["contentType"].Value;
}
else
{
return string.Empty;
}
}

WebAPI IE8、IE9 跨域问题的更多相关文章

  1. 跨域调用webapi web端跨域调用webapi

    web端跨域调用webapi   在做Web开发中,常常会遇到跨域的问题,到目前为止,已经有非常多的跨域解决方案. 通过自己的研究以及在网上看了一些大神的博客,写了一个Demo 首先新建一个webap ...

  2. 使用Cors在WebApi中实现跨域请求,请求方式为angular的 $http.jsonp

    使用Cors在WebApi中实现跨域请求 第一步,在webapi项目中安装cors 在Web API配置文件中(Global.asax)进行全局配置: public class WebApiAppli ...

  3. .net core webapi搭建(2)跨域

    Core WebAPI中的跨域处理 在使用WebAPI项目的时候基本上都会用到跨域处理 Core WebAPI的项目中自带了跨域Cors的处理,不需要单独添加程序包 如图所示 修改 Configure ...

  4. 彻底解决Asp.netCore WebApi 3.1 跨域时的预检查204 options重复请求的问题

    Asp.netCore WebApi 3.1 跨域的预检查options问题 1:我们直接使用core跨域的中间件 ,注入跨域服务, services.AddCors(options => { ...

  5. IE9 IE8 ajax跨域问题的解决

    项目中用到的跨域 ,在除IE9以下的浏览器上运行都是没有问题的,IE8 IE9中报错,error :no transport; 网上解决办法均是 在发起请求之前添加 jQuery.support.co ...

  6. c# WebApi之解决跨域问题:Cors

    什么是跨域问题 出于安全考虑,浏览器会限制脚本中发起的跨站请求,浏览器要求JavaScript或Cookie只能访问同域下的内容.由于这个原因,我们不同站点之间的数据访问会被拒绝. Cors解决跨域问 ...

  7. webapi 解决ajax跨域请求问题

    webapi在配置文件中加入这几句就可以解决ajax(同源策略是JavaScript里面的限制,其他的编程语言,比如在C#,Java或者iOS等其他语言中是可以调用外部的WebService,也就是 ...

  8. IE8浏览器跨域接口访问异常的解决办法

    IE8版本以下浏览器绝对是一个神奇的存在,忙碌好久,万事具备,居然在ajax调用接口的时候直接爆炸 陈述一下问题 首先是有这样一个接口,请求类型POST,入参JSON,出参JSON,jQuery aj ...

  9. WebApi(一)-实现跨域返回格式支持json

    1.创建webapi

随机推荐

  1. Asphalting Roads(翻译!)

    Description City X consists of n vertical and n horizontal infinite roads, forming n × n intersectio ...

  2. 解决Ubuntu16.04 fatal error: json/json.h: No such file or directory

    参考博客 错误产生 安装json-c库之后,根据GitHub上面的readme文件链接到json-c库时出现以下错误: SDMBNJson.h:9:23: fatal error: json/json ...

  3. Codeforces Round #287 (Div. 2) E. Breaking Good 最短路

    题目链接: http://codeforces.com/problemset/problem/507/E E. Breaking Good time limit per test2 secondsme ...

  4. 代码查重工具sim

    在瞎搜东西的时候,发现了一个大牛的博客 看起来很厉害的样子...做了一个LaTeX的语法检查并给出适当的提示,上wiki上一查发现他竟然是CVS第一个版本的发明者和开发者...Dick grune这是 ...

  5. C++ Primer Plus学习:第二章

    C++入门第二章:开始学习C++ 进入C++ 首先,以下是一个C++程序: //myfirst.cpp 显示一行文字 #include<iostream> //预处理器编译指令 int m ...

  6. WPF和Expression Blend开发实例:Adorner(装饰器)应用实例

    装饰器-- 表示用于修饰 UIElement 的 FrameworkElement 的抽象类 简单来说就是,在不改变一个UIElement结构的情况下,将一个Visual对象加到它上面. 应用举例: ...

  7. 正规文法转化DFA

    #include<string.h>#include<stdio.h>#include<stdlib.h>int main(){    char p[30][30] ...

  8. crontab部署定时任务

    1.安装cron工具:apt-getinstall cron 2.开启定时任务:crontab –e 定时任务语句格式为:执行周期+命令. 周期有5个域,分别是分,时,日(day of month), ...

  9. IDEA换行CRLF, LF, CR的解释和默认设置

    在window下开发有一个大坑,就是换行默认是CRLF,也就是回车换行,但是Linux下只有换行LF,这样代码提交后,会出现编译问题,所以最好的办法是在IDEA下设置默认为LF. 首先我们先介绍CRL ...

  10. MySql中的varchar类型

    转载:http://www.cnblogs.com/doit8791/archive/2012/05/28/2522556.html 1.varchar类型的变化 MySQL 数据库的varchar类 ...