繁体   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