选项请求不命中控制器

时间:2015-09-01 06:38:11

标签: c# asp.net-mvc iis cors

我有一个需要添加CORS支持的ASP.NET C#MVC Action。我已经添加了标题,当我在本地的单独端口上运行它时,它在添加标题后工作,但在IIS中托管时;请求没有传递给MVC,但是在IIS本身处理,这导致永远不会发送CORS头。我知道可以在IIS中配置它们,但我希望能够在MVC本身的每个请求的基础上执行此操作。

以下是请求:

OPTIONS http://my-server/Producten/Filters HTTP/1.1
Accept: */*
Origin: http://localhost:49188
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, accept
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko
Host: filter.atlassian.nigella.nl
Content-Length: 0
DNT: 1
Connection: Keep-Alive
Pragma: no-cache

以下是回复:

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/8.5
Public: OPTIONS, TRACE, GET, HEAD, POST
X-Powered-By: ASP.NET
Date: Tue, 01 Sep 2015 06:25:59 GMT
Content-Length: 0

我添加了这些处理程序覆盖以确保" OPTIONS"请求应通过:

<system.webServer>
      <handlers>
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      </handlers>
    </system.webServer>

以下是行动:

    const string HTTP_METHOD_GET = "GET";
    const string HTTP_METHOD_POST = "POST";
    const string HTTP_METHOD_OPTIONS = "OPTIONS";
    [AcceptVerbs(HTTP_METHOD_GET, HTTP_METHOD_POST, HTTP_METHOD_OPTIONS)]
    public ActionResult GetFilters(Models.Filter[] filters, List<int> productcodes)
    {
        Response.Headers.Add("Access-Control-Allow-Origin", "*");
        Response.Headers.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        // Handle options
        if (Request.HttpMethod == HTTP_METHOD_OPTIONS)
        {
            return new ContentResult() { Content = "O Hai!" };
        }
        else
        {
            // other code to execute normally here
        }
    }

0 个答案:

没有答案