我在创建Web API时遇到问题,如果我从同一个域调用它,API可以正常工作,但在CORS开始行动时(来自其他域)则不能正常工作
我有一个控制器方法,而不是验证用户并获得一个身份验证令牌:
[ApiAuthenticationFilter]
public class AuthenticateController : ApiController
{
#region Private variable.
private readonly TokenServices _tokenServices;
#endregion
#region Public Constructor
/// <summary>
/// Public constructor to initialize product service instance
/// </summary>
public AuthenticateController(TokenServices tokenServices)
{
_tokenServices = tokenServices;
}
public AuthenticateController()
{
_tokenServices = new TokenServices();
}
#endregion
[HttpPost]
/// <summary>
/// Authenticates user and returns token with expiry.
/// </summary>
/// <returns></returns>
public HttpResponseMessage Authenticate()
{
if (System.Threading.Thread.CurrentPrincipal != null && System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
var basicAuthenticationIdentity = System.Threading.Thread.CurrentPrincipal.Identity as BasicAuthenticationIdentity;
if (basicAuthenticationIdentity != null)
{
var userId = basicAuthenticationIdentity.UserId;
return GetAuthToken(userId);
}
}
return null;
}
我用这种方式用另一个应用程序的ajax调用此方法:
var settings = {
"async": false,
"error": function (req, status, error) {
alert(status);
},
"success": function (responseData, textStatus, jqXHR) {
alert("acierto");
},
"crossDomain": true,
"contentType" : 'application/json; charset=utf-8',
"url": "http://localhost:18883/api/authenticate",
"method": "POST",
"headers": {
"authorization": "Basic" + authorizationBasic,
"cache-control": "no-cache",
}
}
$.ajax(settings).done(function (response) {
console.log("error");
});
我已经像这样设置了我的CORS处理程序:
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
var tcs = new TaskCompletionSource<HttpResponseMessage>();
tcs.SetResult(response);
return tcs.Task;
}
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
return base.SendAsync(request, cancellationToken);
}
并在我的global.asax
中注册了处理程序 GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
然而,当我发送POST方法时,我的CORS消息处理程序获取选项消息而下一条消息而不是POST是一个用url中的用户和密码获取,所以我在y客户端找到一个方法不允许响应应用