簡體   English   中英

ASP.NET Web窗體:所請求的資源上不存在“ Access-Control-Allow-Origin”標頭

[英]ASP.NET Web Forms: No 'Access-Control-Allow-Origin' header is present on the requested resource

我知道有人問過類似的問題,但我幾乎嘗試了所有問題,但沒有一個起作用。

我只需要簡單地允許一個單獨的網站(mywebsite.com)來訪問另一個Web服務(myserver.com)的Web API方法(在ASP.NET Web API上編碼並在Azure上托管)

服務器代碼:

public class MyController : ApiController
{
     [EnableCors(origins: "http://mywebsite.com", headers: "*", methods: "*")]
     [Route("api/sendrequest")]
     [HttpPost]
     public IHttpActionResult SendRequest()
     {
          string response = "You made it to the server!";

          return Ok(new { response });
     }
}

客戶端Ajax請求:

function send_data() {

    var values = "Hello from Client";

    $.ajax({
        url: "https://myserver.com/api/mycontroller/sendrequest",
        type: "POST",
        data: values,
        success: function (response) {
            alert(response);
            console.log(response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
            alert("error");
        }

    });
}

即使允許該特定網站與服務器通信,它仍會在控制台中向我返回此錯誤:

XMLHttpRequest無法加載https://myserver.com/api/mycontroller/sendrequest

所請求的資源上沒有“ Access-Control-Allow-Origin”標頭。 因此,不允許訪問來源“ http://mywebsite.com ”。 響應的HTTP狀態碼為500。

我在這里做錯了什么? 我是否應該在請求標頭中包含任何其他詳細信息?

您需要配置您的web.config!

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, soapaction" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

暫無
暫無

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

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