【问题标题】:Asp.net WebApi - CORS policyAsp.net WebApi - CORS 策略
【发布时间】:2021-07-20 18:08:51
【问题描述】:

我有 Asp.net web api 项目作为后端 并将 js 反应为前端 我正在尝试通过我的 React 发出 api 请求,以使用我创建的后端的 api 端点从数据库获取或发布数据。

我第一次遇到 GET 和 POST 请求的 CORS 错误, 然后我将此添加到我的 Web.config 文件中

<system.webServer>
  <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
       <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
       <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Pragma, Cache-Control, Authorization " />
     </customHeaders>
   </httpProtocol>
  </system.webServer>

现在 GET 工作正常,但 POST 不工作

获取

public IHttpActionResult Get(string password)
        {
            if (password == "000")
            {
                using (DbModel dbModel = new DbModel())
                {
                    return Ok(dbModel.Provider_status.ToList());
                }
            }
            else
            {
                return null;
            }
        }

发布

[HttpPost]
        public IHttpActionResult Post(List<Provider_status> rows)
        {
            try
            {
                using (DbModel dbModel = new DbModel())
                {
                    dbModel.Provider_status.AddRange(rows);
                    dbModel.SaveChanges();
                }
            }
            catch { }
            return Ok("record created");
        }

【问题讨论】:

标签: asp.net asp.net-mvc asp.net-web-api cors


【解决方案1】:

安装 Cors 包。

  1. 安装包 Microsoft.AspNet.WebApi.Cors

  2. 在您的 WebApiConfig 中启用 Cors

    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
  1. 像这样装饰你的控制器
   [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController

来源:Microsoft Documentation

【讨论】:

  • 我可以设置原点:“*”吗?
  • [EnableCors(origins: "", headers: "", methods: "")] 我将它添加到我的控制器中,现在 GET 和 POST 执行不起作用,我收到此错误消息:被 CORS 策略阻止:“Access-Control-Allow-Origin”标头包含多个值“、*”,但只允许一个。
  • 您可以将全局策略添加到您的 Web 配置中,例如: //Global Policies EnableCorsAttribute cors = new EnableCorsAttribute("", "", "GET,POST,UPDATE" ); config.EnableCors(cors);或 //为特定控制器启用 CORS config.EnableCors(); [EnableCorsAttribute("", "", "*")]
  • 我在这里找到了解决方案stackoverflow.com/questions/54632435/…
猜你喜欢
  • 1970-01-01
  • 2020-07-09
  • 2021-09-15
  • 2021-09-30
  • 2021-11-13
  • 2017-05-25
  • 2015-08-17
  • 2020-11-02
  • 2021-02-22
相关资源
最近更新 更多