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

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

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

在“http://localhost:3273/Values/GetString/1”访问 XMLHttpRequest '来自原产地' 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()
        {
        }
    }

}

最佳答案

这里,

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

}

关于c# - 如何在 asp.net 自托管 API 中启用 CORS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607721/

相关文章:

c# - ImmutableArray如何正确使用

c# - 为什么在 .NET 5 中指定循环枚举值时,枚举的顺序很重要?

asp.net - MVC 中的 HTTPContext 和 ControllerContext

asp.net - 如何捕获 ObjectDataSource.Updata() 的异常

asp.net - 如何将作为 ASP.NET 图像控件提供的图像居中?

node.js - AngularJS $resource 为 $save 方法发出 HTTP OPTIONS 请求而不是 HTTP POST

c# - 使用 LINQ select 过滤 Dictionary<string, string>

c# - Lock 语句 - 它总是释放锁吗?

youtube-api - 上传到 YouTube API 时缺少“Access-Control-Allow-Origin”

angularjs - CORS:AngularJS + Resteasy 3 + Wildfly