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

时间:2019-02-09 15:29:22

标签: c# asp.net cors self-host-webapi

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

CORS策略已阻止从源“ http://localhost:3273/Values/GetString/1”访问“ http://localhost:4200”处的XMLHttpRequest:没有“ 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 个答案:

答案 0 :(得分:2)

在这里

经过大量研究,我找到了解决该问题的方法。 您只需要安装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()
        {
        }
    }

}