【问题标题】:ASP.NET Core Web API POST No 'Access-Control-Allow-Origin' header is presentASP.NET Core Web API POST 不存在“Access-Control-Allow-Origin”标头
【发布时间】:2017-05-01 15:02:41
【问题描述】:

我在另一个控制器中有一个 GET Web API 方法,它与 UseCors 一起正常工作,允许在 Startup.cs 中启用任何来源

当我尝试调用 POST 方法时,我得到一个 No 'Access-Control-Allow-Origin' header is present 错误返回以及 500 错误。

我做错了什么?

using System.Collections.Generic;
using CrossSell.Business.Exceptions;
using CrossSell.Business.Interfaces;
using CrossSell.Entities;
using Microsoft.AspNetCore.Mvc;

namespace CrossSell.API.Controllers
{
    [Produces("application/json")]
    [Route("api/Product")]
    public class ProductController : Controller
    {
        private readonly IProductManager productManager;

        public ProductController(IProductManager productManager)
        {
            this.productManager = productManager;
        }

        // POST: api/Product
        [HttpPost]
        public IEnumerable<Opportunity> Post([FromBody]ClientIdentifiable[] clients)
        {
            try
            {
                return productManager.GetCrossSellOpportunities(clients);
            }
            catch (NoInForceOrHistoricalPoliciesException)
            {
                return new[] { new Opportunity(true, "No In Force or historical policies") };
            }
        }

    }
}

我正在从我的 React 应用程序(在 localhost:3000 上运行)调用 Post 方法:

  getDashboardData() {
    var self = this;
    axios.post( 'http://localhost:5000/product/api/', this.state.clientIdentifiables).then(function (response) {           
           console.log(response);
        });
  }

【问题讨论】:

  • 您能尝试调试错误吗?然后你发 POST /product/ 而不是 api/product/
  • 感谢更正了 api/产品。它正在调用那条路径。
  • 有趣的是,@IlyaChumakov 我无法回答您调试错误的问题,所以我开始调试并发现了问题。

标签: reactjs .net-core asp.net-core-webapi


【解决方案1】:

我忘记在 Startup.cs 的 ConfigureServices 方法中添加依赖注入条目

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddTransient<IClientManager, ClientManager>();
            services.AddTransient<IClientRepository, ClientRepository>();

            // added the following and it hit the web api method correctly
            services.AddTransient<IProductManager, ProductManager>();
            services.AddTransient<IProductRepository, ProductRepository>();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-18
    • 2016-05-13
    • 2019-01-12
    • 1970-01-01
    • 2020-11-06
    • 2017-04-11
    • 2018-10-28
    • 1970-01-01
    相关资源
    最近更新 更多