如何处理ASP.NET MVC中的“OPTIONS方法”

时间:2011-08-09 19:30:27

标签: ajax asp.net-mvc-3 http-options-method

我的Sencha Touch应用程序正在将表单发布到我的 WebService,但不是发送POST,而是发送OPTIONS

我正在阅读类似的帖子here,但我不知道如何在我的代码中处理OPTIONS方法。

我尝试将[AllowAjax]属性添加到我的Action中,但它似乎不存在于MVC3中。

  
    

OPTIONS / GetInTouch / CommunicateCard HTTP / 1.1
    主持人:webservice.example.com
    推荐人:http://192.168.5.206/     访问控制请求方法:POST
    来源:http://192.168.5.206
    用户代理:Mozilla / 5.0(Macintosh; Intel Mac OS X 10_7_0)AppleWebKit / 534.24(KHTML,与Gecko一样)Chrome / 11.0.696.71 Safari / 534.24
    访问控制请求标题:X-Requested-With,Content-Type
    接受: /
    Accept-Encoding:gzip,deflate,sdch
    接受语言:en-US,en; q = 0.8
    Accept-Charset:ISO-8859-1,utf-8; q = 0.7,*; q = 0.3

  

在我的ActionMethod中,我使用以下代码。

    public JsonpResult CommunicateCard(CommunicateCard communicateCard)
    {

        // Instantiate a new instance of MailMessage
        MailMessage mMailMessage = new MailMessage();

        // removed for security/brevity

        // Set the body of the mail message
        mMailMessage.Body = communicateCard.name; // THIS IS CURRENTLY BLANK :-(

        // removed for security/brevity
        mSmtpClient.Send(mMailMessage);

        // do server side validation on form input
        // if it's valid return true
        // else return false
        // currently returning NULL cuz I don't care at this point.
        return this.Jsonp(null);
    }

6 个答案:

答案 0 :(得分:12)

原来我必须创建一个ActionFilterAttribute

namespace WebService.Attributes
{
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Cache.SetNoStore();

            filterContext.RequestContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");

            string rqstMethod = HttpContext.Current.Request.Headers["Access-Control-Request-Method"];
            if (rqstMethod == "OPTIONS" || rqstMethod == "POST")
            {
                filterContext.RequestContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                filterContext.RequestContext.HttpContext.Response.AppendHeader("Access-Control-Allow-Headers", "X-Requested-With, Accept, Access-Control-Allow-Origin, Content-Type");
            }
            base.OnActionExecuting(filterContext);
        }
    }
}

答案 1 :(得分:7)

我在MVC和IIS中以不同的方式解决了这个问题。我发现这个问题的原因是因为我想从客户端javascript(JSONP不起作用)POST数据,并且最重要的是希望允许JSON数据位于POST请求的内容中。

实际上,您的代码想要忽略第一个CORS OPTIONS请求,因为这可能是“站点范围设置”,而不是每个API调用设置。

首先我配置IIS发送CORS响应,这可以通过IIS管理器(或通过web.config更新)完成,如果您使用IIS然后转到要添加这两个值的站点:

  • Access-Control-Allow-Origin为“*”(为了测试,为了更高的安全性,您可能希望将其限制为某些调用域)
  • Access-Control-Allow-Headers,“Content-Type,Accept”(这是用于发布JSON数据)

然后我创建了一个自定义ActionFilter,它必须应用于您想要接受POST数据的每个控制器,这可能会触发CORS请求。自定义操作过滤器是:

public class CORSActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.HttpMethod == "OPTIONS")
        {
            // do nothing let IIS deal with reply!
            filterContext.Result = new EmptyResult();
        }
        else
        {
            base.OnActionExecuting(filterContext);
        }
    }
}

然后在每个控制器的开头,您需要将其应用于添加属性,例如:

[CORSActionFilter]
public class DataSourcesController : Controller

现在我确信在您的整个MVC解决方案中有一种方法可以做到这一点(欢迎解决方案),但是需要进行烧烤并且上面的解决方案有效!

答案 2 :(得分:5)

我将以下内容添加到我的<system.webServer>配置部分:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, X-Requested-With"/>
    <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS"/>
    <add name="Access-Control-Allow-Origin" value="*"/>
  </customHeaders>
</httpProtocol>

答案 3 :(得分:3)

回答问题为什么是“OPTIONS”而不是“POST”,这是因为浏览器正在实施CORS(Cross-origin resource sharing)。 这是首先发送OPTIONS请求的两部分过程,然后如果服务器回复可接受的条件,则浏览器然后将数据/内容的实际请求发送到。

答案 4 :(得分:1)

我在这里尝试了所有的答案,但都没有效果。我最终意识到,如果它返回非200,浏览器会将飞行前检查视为失败。在我的情况下,IIS返回404,即使有标题。这是因为我的控制器方法有2个属性 - [HttpPost]和[HttpOptions]。显然,这不是表达多个动词的有效机制。我不得不使用这个属性:[AcceptVerbs(HttpVerbs.Options | HttpVerbs.Post)]

答案 5 :(得分:1)

经过很多努力之后,我发现处理CORS预检请求的唯一方法是使用一对HttpModule和HttpHandler来处理它。 仅发送所需的标头是不够的。您必须尽早处理OPTIONS请求,并且不允许它到达您的控制器,因为它在那里将失败。

我唯一可以做到这一点的方法就是使用HttpModule。

我关注了这篇博客文章:

http://geekswithblogs.net/abhijeetp/archive/2016/06/04/adding-cors-support-for-asp.net--webapi-the-no-hassle.aspx

总结一下工作,这是代码:

namespace WebAPI.Infrastructure
{
    using System;
    using System.Web;
    using System.Collections;
    using System.Net;
    public class CrossOriginModule : IHttpModule
    {
        public String ModuleName
        {
            get { return "CrossOriginModule"; }
        }

        public void Init(HttpApplication application)
        {
            application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
        }

        private void Application_BeginRequest(Object source, EventArgs e)
        {
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;
            CrossOriginHandler.AddCorsResponseHeaders(context);
        }

        public void Dispose()
        {
        }
    }

    public class CrossOriginHandler : IHttpHandler
    {
        #region Data Members
        const string OPTIONS = "OPTIONS";
        const string PUT = "PUT";
        const string POST = "POST";
        const string PATCH = "PATCH";
        static string[] AllowedVerbs = new[] { OPTIONS, PUT, POST, PATCH };
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
        const string AccessControlAllowCredentials = "Access-Control-Allow-Credentials";
        const string AccessControlMaxAge = "Access-Control-Max-Age";
        const string MaxAge = "86400";
        #endregion

        #region IHttpHandler Members
        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            switch (context.Request.HttpMethod.ToUpper())
            {
                //Cross-Origin preflight request
                case OPTIONS:
                    AddCorsResponseHeaders(context);
                    break;

                default:
                    break;
            }
        }
        #endregion

        #region Static Methods
        public static void AddCorsResponseHeaders(HttpContext context)
        {
            if (Array.Exists(AllowedVerbs, av => string.Compare(context.Request.HttpMethod, av, true) == 0))
            {
                var request = context.Request;
                var response = context.Response;
                var originArray = request.Headers.GetValues(Origin);
                var accessControlRequestMethodArray = request.Headers.GetValues(AccessControlRequestMethod);
                var accessControlRequestHeadersArray = request.Headers.GetValues(AccessControlRequestHeaders);
                if (originArray != null &&
                    originArray.Length > 0)
                    response.AddHeader(AccessControlAllowOrigin, originArray[0]);
                response.AddHeader(AccessControlAllowCredentials, bool.TrueString.ToLower());

                if (accessControlRequestMethodArray != null &&
                    accessControlRequestMethodArray.Length > 0)
                {
                    string accessControlRequestMethod = accessControlRequestMethodArray[0];
                    if (!string.IsNullOrEmpty(accessControlRequestMethod))
                    {
                        response.AddHeader(AccessControlAllowMethods, accessControlRequestMethod);
                    }
                }
                if (accessControlRequestHeadersArray != null &&
                    accessControlRequestHeadersArray.Length > 0)
                {
                    string requestedHeaders = string.Join(", ", accessControlRequestHeadersArray);
                    if (!string.IsNullOrEmpty(requestedHeaders))
                    {
                        response.AddHeader(AccessControlAllowHeaders, requestedHeaders);
                    }
                }
            }
            if (context.Request.HttpMethod == OPTIONS)
            {
                context.Response.AddHeader(AccessControlMaxAge, MaxAge);
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.End();
            }
        } 
        #endregion
    }
}

并将它们添加到web.config

<system.webServer>  
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
      <add name="CrossOriginModule" preCondition="managedHandler" type="WebAPI.Infrastructure.CrossOriginModule, Your_Assembly_Name" />
    </modules>
    <handlers>
      <remove name="WebDAV"/>
      <remove name="OPTIONSVerbHandler"/>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." 
           verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." 
           verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." 
           verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
      <add name="CrossOrigin" verb="OPTIONS" path="*" type="WebAPI.Infrastructure.CrossOriginHandler, Your_Assembly_Name" />
    </handlers>   
     <security>
       <authorization>
         <remove users="*" roles="" verbs=""/>
         <add accessType="Allow" users="*" verbs="GET,HEAD,POST,PUT,PATCH,DELETE,DEBUG"/>
       </authorization>
     <requestFiltering>
       <requestLimits maxAllowedContentLength="6000"/>
       <verbs>
         <remove verb="OPTIONS"/>
         <remove verb="PUT"/>
         <remove verb="PATCH"/>
         <remove verb="POST"/>         
         <remove verb="DELETE"/>
       </verbs>
     </requestFiltering>
   </security> 
  </system.webServer>

这适用于Web API和MVC。