Javascript CORS在本地运行良好,但在使用Azure网站时会中断
我正在使用Angular JS构建SPA应用程序,后端是使用承载令牌的asp.net WebAPI。我有一个有趣的问题,应用程序在我的本地机器上运行良好,但当我将其上传到azure网站时,我突然收到一个CORS错误,我不确定根本原因。有趣的是,我可以很好地登录到应用程序,获得承载令牌,但我无法访问任何控制器方法。下面的代码显示了localhost,但很明显,当我上传到Azure网站时,服务名称已被替换 我得到的错误是Javascript CORS在本地运行良好,但在使用Azure网站时会中断,javascript,angularjs,azure,asp.net-web-api,Javascript,Angularjs,Azure,Asp.net Web Api,我正在使用Angular JS构建SPA应用程序,后端是使用承载令牌的asp.net WebAPI。我有一个有趣的问题,应用程序在我的本地机器上运行良好,但当我将其上传到azure网站时,我突然收到一个CORS错误,我不确定根本原因。有趣的是,我可以很好地登录到应用程序,获得承载令牌,但我无法访问任何控制器方法。下面的代码显示了localhost,但很明显,当我上传到Azure网站时,服务名称已被替换 我得到的错误是 "XMLHttpRequest cannot load https://tra
"XMLHttpRequest cannot load https://tradesservice.azurewebsites.net/api/OpenPnL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://perseus1.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 500."
Perseus1当然是我的angular应用程序,tradesservice是我的后端API
发出请求的代码如下所示:
perseusApp.factory('openpnlData', function ($resource,currentUser) {
return $resource('http://localhost:36080/api/OpenPnL/:id', null,
{
'get': {
headers: { 'Authorization': 'Bearer ' + currentUser.getProfile().token },
isArray: true
},
'save': {
headers: { 'Authorization': 'Bearer ' + currentUser.getProfile().token }
},
'update': {
method: 'PUT',
headers: { 'Authorization': 'Bearer ' + currentUser.getProfile().token }
}
});
}))
基本上,我的控制器在用户经过身份验证后调用angular服务来获取数据
控制器代码当前配置为允许来自任何地方的请求
namespace TradesService.Controllers
{
[Authorize]
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class OpenPnLController : ApiController
{
private benderEntities db = new benderEntities();
// GET: api/OpenPnL
public IQueryable<OpenPnL> GetOpenPnL()
{
return db.OpenPnL;
}
// GET: api/OpenPnL/5
[ResponseType(typeof(OpenPnL))]
public IHttpActionResult GetOpenPnL(int id)
{
OpenPnL openPnL = db.OpenPnL.Find(id);
if (openPnL == null)
{
return NotFound();
}
return Ok(openPnL);
}
我还为令牌服务启用了它
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
我得到的答复是
HTTP/1.1 500 Internal Server Error
Cache-Control: private
Content-Length: 36
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Set- Cookie:ARRAffinity=b0cea33dbc4e2efdaae3fe9feccd731de0b41e0e9fe1259e0169810645b448f9;Path=/;Domain=tradesservice.azurewebsites.net
Date: Tue, 06 Oct 2015 23:15:21 GMT
chrome中的javascript控制台显示以下内容
XMLHttpRequest cannot load https://tradesservice.azurewebsites.net/api/OpenPnL. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://perseus1.azurewebsites.net' is therefore not allowed access. The response had HTTP status code 500.
你觉得我做错了什么吗
更新
有人提到服务器配置可能是个问题。以下是web api的web.config的相关部分
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
及回应
HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Content-Length: 0
Server: Microsoft-IIS/8.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=b0cea33dbc4e2efdaae3fe9feccd731de0b41e0e9fe1259e0169810645b448f9;Path=/;Domain=tradesservice.azurewebsites.net
Date: Tue, 06 Oct 2015 23:59:16 GMT
没有更多的错误 响应中没有CORS头,但它不是(必然)CORS错误,存在某种内部服务器错误,如500响应中所示。确保它接受所述的选项请求,查看网络选项卡并检查选项头
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,HEAD,PUT,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Olaround-Debug-Mode, Authorization, Accept" />
<add name="Access-Control-Expose-Headers" value="X-Olaround-Debug-Mode, X-Olaround-Request-Start-Timestamp, X-Olaround-Request-End-Timestamp, X-Olaround-Request-Time, X-Olaround-Request-Method, X-Olaround-Request-Result, X-Olaround-Request-Endpoint" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
OPTIONS /api/OpenPnL HTTP/1.1
Host: tradesservice.azurewebsites.net
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: GET
Origin: https://perseus1.azurewebsites.net
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: https://perseus1.azurewebsites.net/openpnl
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Content-Length: 0
Server: Microsoft-IIS/8.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-Powered-By: ASP.NET
Set-Cookie: ARRAffinity=b0cea33dbc4e2efdaae3fe9feccd731de0b41e0e9fe1259e0169810645b448f9;Path=/;Domain=tradesservice.azurewebsites.net
Date: Tue, 06 Oct 2015 23:59:16 GMT