请求后出现角度ERR_CONNECTION_REFUSED错误

时间:2020-08-01 00:32:13

标签: .net angular http

我正在使用CORS通过.NET WebAPI将Angular连接到数据库,但出现此错误:

enter image description here

我无法确定问题是在Angular还是在.NET方面,因此可以提供任何帮助。这是我的角度组件+服务。让我知道您是否需要更多信息:

export class SleepComponent implements OnInit {

  constructor(public service : SleepService) { }

  ngOnInit(): void {
    this.resetForm();
  }

  resetForm(form?: NgForm) {
    if(form!=null)
    form.resetForm();
    this.service.formData = {
      SleepId : null,
      Start: '',
      Finish: '', 
    }
  }

  onSubmit(form : NgForm) {
      this.insertRecord(form)
  }

  insertRecord(form: NgForm) {
    console.log(this.service.formData.Finish)
    this.service.postSleep(form.value).subscribe(
      res=> { this.resetForm(form) }
    ), 

      err => {
      console.log(err);
    }
  }
export class SleepService {

  formData: Sleep;
  readonly rootUrl = "https://localhost:44398/api"

  constructor(private http: HttpClient) { }

  postSleep (formData: Sleep) {
    return this.http.post(this.rootUrl+'/main_tb', formData )

  }

这是api控制器:

     [ResponseType(typeof(main_tb))]
        public IHttpActionResult Postmain_tb(main_tb main_tb)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.main_tb.Add(main_tb);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = main_tb.SleepId }, main_tb);
        }

这是webconfig.cs

{

            //Enable CORS
            config.EnableCors(new EnableCorsAttribute("http://localhost:4200/", headers:"*", methods: "*"));
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

1 个答案:

答案 0 :(得分:-1)

请在您的网络配置中添加以下配置

<httpProtocol>
      <customHeaders>
  <add name="Access-Control-Allow-Origin" value="*" />
  <add name="Access-Control-Allow-Headers" value="accept,accesstoken,authorization,cache- 
  control,pragma,content-type,origin" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS,TOKEN" />
      </customHeaders>
    </httpProtocol>

这是webapi cors config

var cors = new EnableCorsAttribute("http://localhost, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS,TOKEN");
    config.EnableCors(cors);

如果它在Postman上不能正常工作,而在浏览器中不能正常工作,那么它可以解决CORS问题,您可以在检查网络标签中检查飞行前请求(OPTIONS),请确认其工作正常