簡體   English   中英

為ASP.NET Web窗體ApiController啟用Http選項預檢請求

[英]Enable Http Options Preflight Request For ASP.NET Web Forms ApiController

我有一個帶有幾個API控制器的ASP.NET Web表單應用程序。 我的一個控制器從另一個域獲取請求。 由於此請求包含一個Authorization標頭,因此瀏覽器將發送預檢請求(HTTP OPTIONS)。 首先,我嘗試在Web配置中添加以下內容:

 <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Expose-Headers " value="WWW-Authenticate"/>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, PATCH, DELETE"/>
    <add name="Access-Control-Allow-Headers" value="accept, authorization, Content-Type"/>
    <remove name="X-Powered-By"/>
  </customHeaders>
</httpProtocol>

但是它不起作用,並且瀏覽器因“ 405-不允許使用方法”錯誤而失敗。 僅在將以下代碼添加到global.asax時,我才成功收到預檢請求

    protected void Application_BeginRequest(object sender, EventArgs e)
{
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        //These headers are handling the "pre-flight" OPTIONS call sent by the browser
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
        HttpContext.Current.Response.AddHeader("Access-Control-Allow‌-Credentials", "true");
        HttpContext.Current.Response.End();
    }
}

讓我感到困擾的是,此代碼為所有Web API控制器啟用了預檢請求,而我只想為我的一個控制器啟用它。 我知道我可以使用帶有[HttpOptions]批注的函數來解決它,但是我不想為控制器中的每個函數添加它。 有沒有辦法為所有控制器功能啟用它?

將此方法添加到Global.asax.cs並放置此代碼

using System.Web;

namespace Example
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }
    }
}

不錯的博客給你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM