在Azure移动服务中启用CORS - 未授权的选项

时间:2014-06-10 00:15:55

标签: c# azure asp.net-web-api cors azure-mobile-services

我正在使用Azure移动服务创建.Net Web服务。服务本身工作正常,但我想启用CORS。

我的Global.asax包含:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod != "OPTIONS") return;
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
        "Authorization, Origin, Content-Type, Accept, X-Requested-With,x-zumo-application,x-zumo-installation-id");
    HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
    HttpContext.Current.Response.End();
}

我的WebAPIConfig.cs包含:

    public static void Register()
    {
        ConfigOptions options = new ConfigOptions();
        HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));

        var cors = new EnableCorsAttribute("*", "*", "*","*");
        config.EnableCors(cors);

        config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
    }

我的要求/回复:

OPTIONS http://********.azure-mobile.net/API/MyLogin?username=username&password=password&email=testtest%40example.com&_=140191793307 HTTP/1.1
Host: ********.azure-mobile.net
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: null
Access-Control-Request-Method: GET
Access-Control-Request-Headers: content-type,x-zumo-application,x-zumo-installation-id
Connection: keep-alive
Cache-Control: max-age=0


HTTP/1.1 401 Unauthorized
Content-Length: 81
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/8.0
WWW-Authenticate: Basic realm="Service"
X-Powered-By: ASP.NET
Set-Cookie:    ARRAffinity=50b9234b61ec5f663e817ec57c430ca7b921bbcd842719dfc2bdc27374adea87;Path=/;Domain=********.azure-mobile.net
Date: Wed, 04 Jun 2014 21:38:56 GMT

<Error><Message>Authorization has been denied for this request.</Message></Error>

1 个答案:

答案 0 :(得分:1)

此处有一个在移动服务中启用CORS的解决方法:

https://gist.github.com/HenrikFrystykNielsen/6c934be6c6c8fa9e4bc8

您不需要Application_BeginRequest部分 - 请求/响应不通过该代码路径 - 它们通过OWIN管道。好的是你只需要上面的要点就可以了。

希望这有帮助!

的Henrik