WEBAPI中的CORS实现 - .net framework 4.0

时间:2014-03-13 09:44:13

标签: .net asp.net-web-api cors

我对webAPi有点新意,我想在Web API上实现CORS(跨源资源共享)。我指的是Microsoft link。他们使用

安装Nuget包
PM> Install-Package Microsoft.AspNet.Cors -Version 5.0.0-rc1 -Pre

但是,我使用的是.NET Framework 4.0,但它无法运行。之后我使用了这个Nuget命令:

Install-Package Microsoft.AspNet.WebApi -Version 4.0.20710

但它不包含CORS类。那么,我们还有其他任何不同的方式来实现CORS吗?

2 个答案:

答案 0 :(得分:4)

我使用以下内容并且可以正常使用(我不确定" 4.0客户端配置文件"位):

public class CorsHandler : DelegatingHandler
{
    private const string Origin = "Origin";
    private const string AccessControlRequestMethod = "Access-Control-Request-Method";
    private const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
    private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
    private const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
    private const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

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);
        }
    }

请记住在app start(我在global.asax中)注册

GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());

答案 1 :(得分:0)

需要.NET Framework 4.5和visual studio / express 2014的Web API 2支持CORS包。

它不适用于Web API 1(您使用的是.NET 4.0)

参考this thread