如何在 asp.net 自托管 API 中启用 CORS?

KEV*_*HAL 5 c# asp.net cors self-host-webapi

我在 asp.net 中创建了一个自托管的 Web API,当我从 POSTMAN 调用它时它工作正常,但是当我从浏览器调用它时出现以下错误。

从源 ' http://localhost:4200 '访问 XMLHttpRequest at ' http://localhost:3273/Values/GetString/1 '已被 CORS 策略阻止:No '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()
        {
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

KEV*_*HAL 7

这里,

经过如此多的研究,我找到了解决这个问题的方法。你只需要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()
        {
        }
    }

}
Run Code Online (Sandbox Code Playgroud)