Enable CORS in Sharepoint 2013

爱⌒轻易说出口 提交于 2019-12-09 00:52:28

You can change your condition as below. It works well.

    protected void Application_BeginRequest(Object sender, EventArgs e)
    {

        HttpContext InRequest = HttpContext.Current;

        string OldPath = InRequest.Request.Path.ToLower();

        if (OldPath.Contains("myservice.svc"))
        {

            string httpOrigin = Request.Params["HTTP_ORIGIN"];
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", httpOrigin);
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                "GET, POST, PUT, DELETE, OPTIONS");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept, X-Token");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");

            if (Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.StatusCode = 200;
                var httpApplication = sender as HttpApplication;
                httpApplication.CompleteRequest();
            }
        }

    }

Have you tried changing web.config at your IIS' root?

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

http://enable-cors.org/server_iis7.html

It's indeed web config modifications but to get this to work i had to use SPWebConfigModification class

$webApp = Get-SPWebApplication http://myurl/
$modification = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
$modification.Path = "configuration/system.webServer/httpProtocol/customHeaders"
$modification.Name = "add[@name=`"Access-Control-Allow-Origin`"][@value=`"http://theirurl`"]"
$modification.Value = "<add name=`"Access-Control-Allow-Origin`" value=`"http://theirurl`" />"
$modification.Owner = “Administrator”
$modification.Sequence = 0
$modification.Type = 0

if (($webapp.WebConfigModifications | where-object { $_.Name -eq $modification.Name } | measure).Count -eq 0) {
    Write-Host "Adding " $modification.Name
    $webApp.WebConfigModifications.Add($modification)    
}
else {
    Write-Host $modification.Name already added
}
$webApp.Update()
$webApp.WebConfigModifications
$webApp.Parent.ApplyWebConfigModifications()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!