У меня есть отдельный проект web api и отдельный проект UI. Для доступа к веб-API в проекте пользовательского интерфейса я включил CORS
, как показано ниже в WebApiConfig.cs
var cors = new EnableCorsAttribute("http://localhost:49567", "*", "*","*");
config.EnableCors(cors);
В AccountController.cs
, когда [Authorize]
отключено, я могу получить доступ к API со страницы html-проекта пользовательского интерфейса, используя ajax.
$.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});
Но когда я хочу включить [Authorize]
для создания аутентификации токена, сначала вызвав /token
, ошибка 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
});
Мой web.config в проекте web api теперь после редактирования, выполненного после предложения @ arista_14
<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]