我在向其他域上的 Web API 发出 PUT 和 DELETE CORS 请求时遇到一些问题。
我已经通过教程编写了 APIhttp://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#create-webapi-project http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#create-webapi-project.
GET 和 POST 请求工作正常,但 DELETE 和 PUT 则不行。我收到这条消息:
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource.
当我将代码添加到建议的 Web Config 时CORS 支持使用 ASP.NET Web API 进行 PUT 和 DELETE https://stackoverflow.com/questions/12521499/cors-support-for-put-and-delete-with-asp-net-web-api,我只得到第一个错误。
有人可以帮我解决这个问题吗?
您可以添加一个处理程序来处理此类请求。
创建一个从“DelegatingHandler”派生的类:
public class PreflightRequestsHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
{
var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
// Define and add values to variables: origins, headers, methods (can be global)
response.Headers.Add("Access-Control-Allow-Origin", origins);
response.Headers.Add("Access-Control-Allow-Headers", headers);
response.Headers.Add("Access-Control-Allow-Methods", methods);
var tsc = new TaskCompletionSource<HttpResponseMessage>();
tsc.SetResult(response);
return tsc.Task;
}
return base.SendAsync(request, cancellationToken);
}
}
稍后在 WebApiconfig.cs 的 Register 方法中添加以下内容:
public static void Register(HttpConfiguration config)
{
// Define and add values to variables: origins, headers, methods (can be global)
// Enable global CORS
config.EnableCors(new EnableCorsAttribute(origins, headers, methods));
// Add handler to deal with preflight requests, this is the important part
config.MessageHandlers.Add(new PreflightRequestsHandler()); // Defined above
.
.
.
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)