用户登录
用户注册

分享至

基于CORS实现WebApi Ajax 跨域请求解决方法

  • 作者: 烟酒红唇丶贼迷人
  • 来源: 51数据库
  • 2021-08-07

概述

asp.net web api 的好用使用过的都知道,没有复杂的配置文件,一个简单的apicontroller加上需要的action就能工作。但是在使用api的时候总会遇到跨域请求的问题,特别各种app万花齐放的今天,api的跨域请求是不能避免的。

在默认情况下,为了防止csrf跨站的伪造攻击(或者是 javascript的同源策略(same-origin policy)),一个网页从另外一个域获取数据时就会收到限制。有一些方法可以突破这个限制,那就是大家熟知的jsonp, 当然这只是众多解决方法中一种,由于jsonp只支持get的请求,如今的复杂业务中已经不能满足需求。而cors(cross origin resource sharing https://www.w3.org/wiki/cors)跨域资源共享,是一种新的header规范,可以让服务器端放松跨域的限制,可以根据header来切换限制或者不限制跨域请求。重要的是它支持所有http请求方式。

问题

xmlhttprequest 跨域 post或get请求 ,请求方式会自动变成options的问题。

由于cors(cross origin resource share)规范的存在,浏览器会首先发送一次options嗅探,同时header带上origin,判断是否有跨域请求权限,服务器响应access control allow origin的值,供浏览器与origin匹配,如果匹配则正式发送post请求,即便是服务器允许程序跨域访问,若不支持 options 请求,请求也会死掉。

原因

浏览器为了安全起见,会preflighted request的透明服务器验证机制支持开发人员使用自定义的头部、get或post之外的方法,以及不同类型的主题内容,也就是会先发送一个 options 请求,
问问服务器是否会正确(允许)请求,确保请求发送是安全的。

出现 options 的情况一般为:

1、非get 、post请求

2、post请求的content-type不是常规的三个:application/x- www-form-urlencoded(使用 http 的 post 方法提交的表单)、multipart/form-data(同上,但主要用于表单提交时伴随文件上传的场合)、text/plain(纯文本) 

3、post请求的payload为text/html 

4、设置自定义头部

options请求头部中会包含以下头部:origin、access-control-request-method、access-control-request-headers,发送这个请求后,服务器可以设置如下头部与浏览器沟通来判断是否允许这个请求。
access-control-allow-origin、access-control-allow-method、access-control-allow-headers

解决方法

此方法功能强大,可以解决asp.net web api复杂跨域请求,携带复杂头部信息,正文内容和授权验证信息

方法一

public class croshandler:delegatinghandler
{
 private const string origin = "origin";
 private const string accesscontrolrequestmethod = "access-control-request-method";
 private const string accesscontrolrequestheaders = "access-control-request-headers";
 private const string accesscontrolalloworign = "access-control-allow-origin";
 private const string accesscontrolallowmethods = "access-control-allow-methods";
 private const string accesscontrolallowheaders = "access-control-allow-headers";
 private const string accesscontrolallowcredentials = "access-control-allow-credentials";
 protected override task<httpresponsemessage> sendasync(httprequestmessage request, cancellationtoken cancellationtoken)
 {
  bool iscrosrequest = request.headers.contains(origin);
  bool isprefilightrequest = request.method == httpmethod.options;
  if (iscrosrequest)
  {
   task<httpresponsemessage> taskresult = null;
   if (isprefilightrequest)
   {
    taskresult = task.factory.startnew<httpresponsemessage>(() =>
    {
     httpresponsemessage response = new httpresponsemessage(system.net.httpstatuscode.ok);
     response.headers.add(accesscontrolalloworign,
      request.headers.getvalues(origin).firstordefault());
     string method = request.headers.getvalues(accesscontrolrequestmethod).firstordefault();
     if (method != null)
     {
      response.headers.add(accesscontrolallowmethods, method);
     }
     string headers = string.join(", ", request.headers.getvalues(accesscontrolrequestheaders));
     if (!string.isnullorwhitespace(headers))
     {
      response.headers.add(accesscontrolallowheaders, headers);
     }
     response.headers.add(accesscontrolallowcredentials, "true");
     return response;
    }, cancellationtoken);
   }
   else
   {
    taskresult = base.sendasync(request, cancellationtoken).continuewith<httpresponsemessage>(t =>
    {
     var response = t.result;
     response.headers.add(accesscontrolalloworign,
      request.headers.getvalues(origin).firstordefault());
     response.headers.add(accesscontrolallowcredentials, "true");
     return response;
    });
   }
   return taskresult;
  }
  return base.sendasync(request, cancellationtoken);
 }
}

使用方式,在global.asax文件添加

protected void application_start()
{
 iocconfig.registerall();
 arearegistration.registerallareas();
 webapiconfig.register(globalconfiguration.configuration);
 filterconfig.registerglobalfilters(globalfilters.filters);
 routeconfig.registerroutes(routetable.routes);
 bundleconfig.registerbundles(bundletable.bundles);
 globalconfiguration.configuration.messagehandlers.add(new croshandler());
}

方法二

配置文件中添加如下配置,此方法简单,应对简单的跨域请求

<system.webserver>
 <httpprotocol>
  <customheaders>
  <add name="access-control-allow-origin" value="*" />
  <add name="access-control-allow-headers" value="content-type" />
  <add name="access-control-allow-methods" value="get, post,options" />
  </customheaders>
 </httpprotocol>
<system.webserver>

总结

以上所述是小编给大家介绍的基于cors实现webapi ajax 跨域请求解决方法,希望对大家有所帮助

软件
前端设计
程序设计
Java相关