[英]How to enable CORS in asp.net Self-Hosted API?
I created one self-hosted Web API in asp.net it works fine when I call it from POSTMAN but it gives below error when I invoke it from browser. 我在asp.net中创建了一个自托管的Web API,当我从POSTMAN调用它时,它运行正常,但是当我从浏览器调用它时,它会给出以下错误。
Access to XMLHttpRequest at ' http://localhost:3273/Values/GetString/1 ' from origin ' http://localhost:4200 ' has been blocked by CORS policy: No 'Access-Control-A 从' http:// localhost:4200 '访问来自' http:// localhost:3273 / Values / GetString / 1 '的XMLHttpRequest已被CORS策略阻止:否'访问控制-A
Below given is my service class 下面给出的是我的服务类
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()
{
}
}
}
Here, 这里,
I found solution for this problem after so many research. 经过这么多研究,我找到了解决这个问题的方法。 You just need to install Microsoft.AspNet.WebApi.Cors
and use it like config.EnableCors(new EnableCorsAttribute("*", headers: "*", methods: "*"));
您只需安装Microsoft.AspNet.WebApi.Cors
并使用它就像config.EnableCors(new EnableCorsAttribute("*", headers: "*", methods: "*"));
Hope it will help others. 希望它会帮助别人。
Thanks 谢谢
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()
{
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.