簡體   English   中英

如何處理錯誤“對預檢請求的響應未通過訪問控制檢查:'Access-Control-Allow-Credentials'的值”

[英]How to handel error “Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials'”

我正在嘗試將Http POST請求發送到本地主機中的web-api2服務器。 我的客戶端運行在http:// localhost:4200上 ,服務器運行在http:// localhost / MemoryGameServer / api / Test上 (原產地不同)

我有angular7客戶代碼:

signUp(user: User){
        const body : any = {
            "FullName": "FullName",
            "UserName": "UserName",
            "Password": "Password",
            "Email": "Email",
            "UserId": 2
        }

        var headerOptions = new HttpHeaders({ 'Content-Type':'application/json' });

        return this.http.post(this.rootUrl + 'Test1', JSON.stringify(body), {
            headers: headerOptions,
            withCredentials: true
         });
    }   

而且我有Web api 2服務器代碼:

public class clsTest
    {
        public string FullName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public string Email { get; set; }
        public int UserId { get; set; }
    }

    [RoutePrefix("api")]
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    public class MainController : ApiController
    {    
        [Route("Test1"), HttpPost]
        public IHttpActionResult Test1(clsTest data)
        {
            return Ok("OK!!");
        }
    }

我的WebApiConfig.cs文件:(已更新

public static void Register(HttpConfiguration config)
    {
        EnableCorsAttribute cors = new EnableCorsAttribute("http://localhost:4200", "*", "*")
        {
            SupportsCredentials = true                
        };

        config.EnableCors(cors);

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

但我得到了錯誤:

錯誤

網絡標簽

我該如何解決? 我需要將帶有Json對象的http發布請求發送到服務器。

謝謝!

更新:我將此代碼添加到我的web.config文件中:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
    <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Origin" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

現在我收到此錯誤:

錯誤

以下是從Microsoft准則到“啟用CORS”的步驟。

首先,添加CORS NuGet軟件包。

Install-Package Microsoft.AspNet.WebApi.Cors

打開文件App_Start / WebApiConfig.cs。 將以下代碼添加到WebApiConfig.Register方法:

public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

接下來,將[EnableCors]屬性添加到Controller類:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
    public class MainController : ApiController
    {
        // Controller methods not shown...
    }
}

這允許來自WebClient的跨域請求,同時仍然禁止所有其他跨域請求。

原始URL的末尾請勿包含正斜杠。

暫無
暫無

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

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