【发布时间】:2019-01-23 01:00:12
【问题描述】:
我有一个单独的 web api 项目和一个单独的简单 UI 项目。要在 UI 项目中访问 web api,我在 WebApiConfig.cs 中启用了CORS,如下所示
var cors = new EnableCorsAttribute("http://localhost:49567", "*", "*","*");
config.EnableCors(cors);
在 AccountController.cs 中,当 [Authorize] 被禁用时,我可以使用 ajax 从 UI html 项目页面访问 API。
$.ajax({
type: "GET",
url: "http://localhost:51401/api/Account/UserInfo",
data: "",
contentType: "application/json; charset=utf-8",
success: VerifyResponse,
dataType: "json",
crossDomain: true,
failure: ajaxCallFailed});
但是当我想通过首先调用/token 来启用[Authorize] 来创建令牌身份验证时,错误Cross-Origin Request Blocked: 在html 中重复。
$.ajax({
method: "POST",
url: "http://localhost:51401/Token",
data: {
username: $('#username').val(),
password: $('#password').val(),
grant_type: 'password'
},
contentType: "application/json",
success: VerifyResponse,
dataType: "json",
crossDomain: true,
failure: ajaxCallFailed
});
在@arista_14 建议后进行编辑后,我现在在 web api 项目中的 web.config
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
<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>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
现在的错误是:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:51401/Token. (Reason: CORS preflight channel did not succeed).[Learn More]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:51401/Token. (Reason: CORS request did not succeed).[Learn More]
【问题讨论】:
标签: c# asp.net-web-api