Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

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()
        {
        }
    }

}
like image 680
KEVAL PANCHAL Avatar asked Feb 09 '19 15:02

KEVAL PANCHAL


People also ask

How do I enable CORS in self hosting?

AspNet. WebApi. Cors and use it like config. EnableCors(new EnableCorsAttribute("*", headers: "*", methods: "*"));

How do I enable CORS in asp net CORS?

You can enable CORS per action, per controller, or globally for all Web API controllers in your application. To enable CORS for a single action, set the [EnableCors] attribute on the action method.


1 Answers

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: "*"));

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()
        {
        }
    }

}
like image 99
KEVAL PANCHAL Avatar answered Oct 09 '22 05:10

KEVAL PANCHAL