如何在ASP.NET自托管API中启用CORS?

5
我创建了一个自托管的asp.net Web API,当我从POSTMAN调用它时,它可以正常工作,但是当我从浏览器中调用它时,会出现以下错误:
XMLHttpRequest访问 'http://localhost:3273/Values/GetString/1' 从源 'http://localhost:4200' 被CORS策略阻止:没有 'Access-Control-A'。
下面是我的服务类:
using System.Web.Http;
using System.Web.Http.SelfHost;

namespace SFLSolidWorkAPI
{
    public partial class SolidWorkService : ServiceBase
    {
        public SolidWorkService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8069");


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

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();
        }

        protected override void OnStop()
        {
        }
    }

}

1
你尝试过使用Microsoft.AspNet.WebApi.Cors吗?文档请参考https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api - abestrad
是的,我尝试过,但对我没有用。即使我尝试在控制器级别启用cros,但它也不起作用。 - KEVAL PANCHAL
使用类似Wireshark或Fiddler的嗅探器。将Postman的工作结果与不工作的应用程序进行比较。修改应用程序,使HTTP头与Postman相同。 - jdweng
请确保您的服务设置以下标头: "Access-Control-Allow-Origin", "*" "Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With" "Access-Control-Allow-Methods", "GET, PUT, POST" - abestrad
在控制器级别上添加了[EnableCors(origins: "*", headers: "*", methods: "*")],但仍然无法正常工作。 - KEVAL PANCHAL
1个回答

8

在这里,

经过多次研究,我找到了解决这个问题的办法。 您只需安装Microsoft.AspNet.WebApi.Cors,并像这样使用config.EnableCors(new EnableCorsAttribute("*", headers: "*", methods: "*"));

希望这能帮助其他人。

感谢

using System;
using System.ServiceProcess;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.SelfHost;

namespace SFLSolidWorkAPI
{
    public partial class DemoService : ServiceBase
    {
        public DemoService ()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8069");


            config.Routes.MapHttpRoute(
               name: "API",
               routeTemplate: "{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );
            config.EnableCors(new EnableCorsAttribute("*", headers: "*", methods: "*"));

            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();
        }

        protected override void OnStop()
        {
        }
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接