friend 们,
我尝试从 Word 加载项调用 API 并收到“访问被拒绝”错误。我做了一些研究,看起来“跨源资源共享”是原因。
<强>1。网络API
我在本地托管 Web API 2:“http://localhost:61546/api/ORG_NAMES” & 我已启用 CORS 来接受所有来源,请参阅下面的 WebApiConfig。
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
<强>2。测试应用
为了测试这个 API 以确保它支持 CORS,我创建了以下页面并托管在 localhost:52799/home.html 上,我能够得到预期的响应。我已经在 IE 10 和 Chrome 中对此进行了测试。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function () {
var obj;
.support.cors = true;
$.getJSON("http://localhost:61546/api/ORG_NAMES/112233",
function (data) {
alert(data.ORG_ID);
});
});
});
</script>
</head>
<body>
<button>Click me</button>
</body>
<强>3。 Word 插件
现在我想从我的 Word Web 加载项调用此 API。从不同主机运行的 Word 加载项 https://localhost:44339/ ,见下面的代码。这里 getJSON 返回“访问被拒绝”。
var OrgID;
$.getJSON("http://localhost:61546/api/ORG_NAMES/112233",
function (data) {
OrgID = data.ORG_ID;
});
此外,当我从 Word 加载项调用 API 时,它不会出现 fiddler。
注意:这是“Web 加载项 --> Word 加载项”项目。
<强>4。修复 - 需要帮助
不确定为什么我会从 Word-Add-In 收到“访问被拒绝”错误,如果 CORS 是问题所在,那么我的测试应用程序 (#2) 应该无法正常工作,对吗?
我尝试使用“$.ajax”、“XMLHttpRequest”调用 JSON,但它不起作用。我可能缺少一些配置设置。
感谢此处的任何帮助。 如果您需要更多信息,请告诉我。
最佳答案
由于这听起来像是仅 Office 加载项中的问题,而不是常规页面中的问题,您是否尝试过在 list 文件中设置您的 AppDomains
?请参阅 https://dev.office.com/docs/add-ins/overview/add-in-manifests 中的“指定要在加载项窗口中打开的域”
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="TaskPaneApp">
<Id>c6890c26-5bbb-40ed-a321-37f07909a2f0</Id>
<Version>1.0</Version>
<ProviderName>Contoso, Ltd</ProviderName>
<DefaultLocale>en-US</DefaultLocale>
<DisplayName DefaultValue="Northwind Traders Excel" />
<Description DefaultValue="Search Northwind Traders data from Excel"/>
<AppDomains>
<AppDomain>https://www.northwindtraders.com</AppDomain>
</AppDomains>
<DefaultSettings>
<SourceLocation DefaultValue="https://www.contoso.com/search_app/Default.aspx" />
</DefaultSettings>
<Permissions>ReadWriteDocument</Permissions>
</OfficeApp>
关于asp.net-web-api - 来自 Word Web 加载项 (Office.Js) 的 API 调用不起作用 : CORS Issue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38707684/