发布数据时,CORS预检频道未成功

时间:2018-01-23 08:34:29

标签: angularjs asp.net-web-api asp.net-web-api2

我正在开发Web Api服务和Angularjs网站。当我尝试从客户端发布数据到服务器时,我在浏览器控制台中收到以下错误。当我调试它时,控制器构造函数被命中但不是方法。

错误

  

阻止跨源请求:同源策略禁止读取   http://localhost:53269/RegisterUser处的远程资源。 (原因:   CORS预检频道没有成功)。

Web API服务代码

[Authorize]
public class UserController : ApiController
{
    private UnitOfWork unitOfWork = new UnitOfWork();
    private Repository<User> userkRepository;

    public UserController()
    {
        userkRepository = unitOfWork.Repository<User>();
    }

    [HttpPost]
    [Route("RegisterUser")]
    public void RegisterUser([FromBody] User user)
    {
        if (user.UserId == -1)
        {
            userkRepository.Insert(user);
        }           

    }

    [HttpPost, Route("API/Connect")]
    public string  Connect()
    {
        return "User Connected";
    }
}

Angular客户端代码

import { Injectable } from '@angular/core';
import { Http,Response ,Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable'; ///Allow clients to subscribbe responces asnc and add Rx when handling errors catch block
import {User} from './user';
import {HttpClientModule} from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
import 'rxjs/add/operator/map'


@Injectable()
export class UserService {

  constructor( private http : HttpClient) { 

  }


  public RegisterUser(user :User) {

    const headerDict = {
        'Content-Type': 'text/plain',
        'Accept': 'application/json',
        'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': 'true'
      }

      const requestOptions = {                                                                                                                                                                                 
        headers: new HttpHeaders(headerDict), 
      };

      const data = JSON.stringify(user);

      this.http.post("http://localhost:53269/RegisterUser", data, requestOptions).subscribe(data => {
            alert('ok');
      }, error => {
          console.log(error);
      });;

      }



}

1 个答案:

答案 0 :(得分:-1)

尝试在<System.WebServer>代码

之后在API的web.config中添加此内容
<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>