我在其他领域对Web的CORS请求的制作、放置和删除有一些困难。
我已经通过教程http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#create-webapi-project编写了API。
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.当我向WebConfig添加在使用ASP.NET Web支持PUT和DELETE上建议的代码时,我只得到第一个错误。
有人能帮我吗?
发布于 2015-01-28 14:47:54
您可以添加处理程序来处理此类请求。
创建一个从“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中添加以下内容:
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
.
.
.
}发布于 2014-01-23 21:03:27
您对Web所做的AJAX调用正在触发一个飞行前检查(HTTP谓词"OPTIONS")。这需要由您的系统处理,否则您将得到405错误。关于如何做到这一点,这里有几个答案,比如:
如果您遵循以下指导原则,也可以完全避免此飞行前呼叫。
The browser can skip the preflight request if the following conditions are true:
The request method is GET, HEAD, or POST, **and**
The application does not set any request headers other than Accept, Accept-Language, Content-Language, Content-Type, or Last-Event-ID, **and**
The Content-Type header (if set) is one of the following:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain摘自http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api (在“飞行前请求”下):
发布于 2016-06-22 08:53:36
在我的例子中,CORS不适用于具有自定义标头的XHR请求(因为它需要飞行前选项请求)。我按照正式文件中的描述配置了CORS
解决方案是将其添加到web.config中
<system.webServer>
<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>如果没有此配置,IIS将拦截选项请求,并且在添加此配置后,ASP.NET可以处理它。
我在这博客上找到了解决方案。
https://stackoverflow.com/questions/20792950
复制相似问题