none
Web API Cross 跨 Domain 出現『Access-Control-Allow-Origin』問題? RRS feed

  • 問題

  • Web Service 專案

    在『Package Manager Console』裡執行

    Install-Package Microsoft.AspNet.WebApi.Cors

    WebApiConfig.cs

    public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.EnableCors();
    
                // Web API 設定和服務
    
                // Web API 路由
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "ClientApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new
                    {
                        action = "DefaultAction",
                        id = RouteParameter.Optional
                    }
                );
            }

     TestController.cs

    using System.Web.Http.Cors;

    public class TestController : ApiController { [EnableCors(origins: "*", headers: "*", methods: "*")] [ActionName("DefaultAction")] public HttpResponseMessage Get() { return new HttpResponseMessage() { Content = new StringContent("DefaultAction GET: Test message") }; } [ActionName("DefaultAction")] public HttpResponseMessage Post() { return new HttpResponseMessage() { Content = new StringContent("DefaultAction POST: Test message") }; } [ActionName("DefaultAction")] public HttpResponseMessage Put() { return new HttpResponseMessage() { Content = new StringContent("DefaultAction PUT: Test message") }; } [HttpGet] public HttpResponseMessage CustomGet() { return new HttpResponseMessage() { Content = new StringContent("Get: Test message") }; } [HttpPost] public HttpResponseMessage CustomPost() { return new HttpResponseMessage() { Content = new StringContent("POST: Test message") }; } }

    驗證Web API 的運作,執行『啟動但不偵錯』運行『http://localhost:52888/api/test』,看到 response 內容,『GET: Test Message』。

    WebClient 專案

    index.html

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    </head>
    <body>
        <div>
            <select id="method">
                <option value="get">GET</option>
                <option value="post">POST</option>
                <option value="put">PUT</option>
            </select>
            <input type="button" value="Try it" onclick="sendRequest()" />
            <span id='value1'>(Result)</span>
        </div>
    
        <script type="text/javascript">
        // TODO: Replace with the URL of your WebService app
        var serviceUrl = 'http://localhost:52888/api/test';
    
        function sendRequest() {
            var method = $('#method').val();
    
            $.ajax({
                type: method,
                url: serviceUrl
            }).done(function (data) {
                $('#value1').text(data);
            }).error(function (jqXHR, textStatus, errorThrown) {
                $('#value1').text(jqXHR.responseText || textStatus);
            });
        }
        </script>
    </body>
    </html>

    當選擇『GET』點擊『Try it』時,可以正常顯示『DefaultAction GET: Test message』。

    問題:

    當選擇『POST』、『PUT』點擊『Try it』時,發生『No 'Access-Control-Allow-Origin' header is present on the requested resource.』錯誤。

    =========================================

    POST 的錯誤訊息:

    XMLHttpRequest cannot load http://localhost:52888/api/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:30774' is therefore not allowed access.

    =========================================

    PUT 的錯誤訊息:

    OPTIONS http://localhost:52888/api/test k.cors.a.crossDomain.send @ jquery.js:8630n.extend.ajax @ jquery.js:8166sendRequest @ index.html:26onclick @ index.html:15
    index.html:1

    XMLHttpRequest cannot load http://localhost:52888/api/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:30774' is therefore not allowed access. The response had HTTP status code 405.

    =========================================

    不知是否哪裡還要去設定呢?


    • 已編輯 Mr. Kao 2015年7月2日 上午 06:59 補充內容
    2015年7月2日 上午 06:51

解答