Как обработать ошибку «Ответ на предварительный запрос не проходит проверку контроля доступа: значение« Access-Control-Allow-Credentials »» - PullRequest
0 голосов
/ 28 ноября 2018

Я пытаюсь отправить запрос POST Http на сервер 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
         });
    }   

и у меня есть вебКод сервера 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!!");
        }
    }

my 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 }
        );
    }

Но я получаю ошибку:

error

network tab

Как это исправить?Мне нужно сделать http-запрос с объектом Json на сервер.

Спасибо!

ОБНОВЛЕНИЕ: Я добавил этот код в свой файл 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>

И теперь я получаю эту ошибку:

error

1 Ответ

0 голосов
/ 30 ноября 2018

Ниже приведены инструкции 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-адреса источника.

...