简体   繁体   English

Asp.net WebApi - CORS 策略

[英]Asp.net WebApi - CORS policy

I have Asp.net web api project as a backend and react js as front-end I'm trying to make an api requests through my React to get or post data from or to the database using the api endpoints i created an the backend. I have Asp.net web api project as a backend and react js as front-end I'm trying to make an api requests through my React to get or post data from or to the database using the api endpoints i created an the backend.

first time i had CORS error for both GET and POST requests, then i added this to my Web.config file我第一次遇到 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>

now GET is working fine but POST is not working现在 GET 工作正常,但 POST 不工作

Get得到

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

POST邮政

[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");
        }

I've implemented same but got error for multiple origins.我已经实现了相同的但有多个来源的错误。 When I pass multiple origins with comma separated then again I got CORs error.当我用逗号分隔多个来源时,我再次收到 CORs 错误。 So I've implemented Custom CORS policy providers.所以我实现了自定义 CORS 策略提供程序。

I'm having same issue with PUT method.我对 PUT 方法有同样的问题。 The solution is Custom CORS policy providers.解决方案是自定义 CORS 策略提供程序。

The [ EnableCors ] attribute implements the ICorsPolicyProvider interface. [ EnableCors ] 属性实现ICorsPolicyProvider接口。 You can provide your own implementation by creating a class that derives from Attribute and implements ICorsPolicyProvider .您可以通过创建派生自 Attribute 并实现ICorsPolicyProvider的 class 来提供自己的实现。

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]
public class MyCorsPolicyProvider : Attribute, ICorsPolicyProvider 
{
    private CorsPolicy _policy;

    public MyCorsPolicyProvider()
    {
        // Create a CORS policy.
        _policy = new CorsPolicy
        {
            AllowAnyMethod = true,
            AllowAnyHeader = true
        };

        // Add allowed origins.
        _policy.Origins.Add("http://myclient.azurewebsites.net");
        _policy.Origins.Add("http://www.contoso.com");
    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request)
    {
        return Task.FromResult(_policy);
    }
}

Now you can apply the attribute any place that you would put [ EnableCors ].现在您可以将属性应用到您将放置 [ EnableCors ] 的任何位置。

[MyCorsPolicy]
public class TestController : ApiController
{
    .. //

For example, a custom CORS policy provider could read the settings from a configuration file.例如,自定义 CORS 策略提供程序可以从配置文件中读取设置。

As an alternative to using attributes, you can register an ICorsPolicyProviderFactory object that creates ICorsPolicyProvider objects.作为使用属性的替代方法,您可以注册创建ICorsPolicyProvider对象的ICorsPolicyProviderFactory object。

public class CorsPolicyFactory : ICorsPolicyProviderFactory
{
    ICorsPolicyProvider _provider = new MyCorsPolicyProvider();

    public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
    {
        return _provider;
    }
}

To set the ICorsPolicyProviderFactory , call the SetCorsPolicyProviderFactory extension method at startup, as follows:要设置ICorsPolicyProviderFactory ,请在启动时调用SetCorsPolicyProviderFactory扩展方法,如下所示:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.SetCorsPolicyProviderFactory(new CorsPolicyFactory());
        config.EnableCors();

        // ...
    }
}

It should work, But after your deployment if it will not work then Please add the below configuration in your web.config它应该可以工作,但是在您的部署之后如果它不起作用,请在您的 web.config 中添加以下配置

<system.webServer>    
  <modules>    
    <remove name="WebDAVModule" />    
  </modules>    
  <handlers>    
    <remove name="WebDAV" />  
    <remove name="OPTIONSVerbHandler" />  
    <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" modules="ProtocolSupportModule" requireAccess="None" responseBufferLimit="4194304" />
  </handlers>    
</system.webServer>

After deployment just do IISRESET or restart App pool部署后只需执行IISRESET或重新启动应用程序池

Thank you谢谢

Install the Cors package.安装 Cors package。

  1. Install-Package Microsoft.AspNet.WebApi.Cors安装包 Microsoft.AspNet.WebApi.Cors

  2. Enable Cors in your WebApiConfig在您的 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. Decorate your controller like this像这样装饰你的 controller
   [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController

Source: Microsoft Documentation来源: 微软文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM