locked
How to implement CORS in ASP.NET Web API 2.0 RRS feed

  • Question

  • User171227042 posted

    I have been trying to implement CORS in ASP.NET , I have been trying for a whole day , followed many tutorials but it's not working at all. I am trying to recieve the get request and print it on the web page. What am i missing?  and access control allow origin not showing in response header. here is my code

        

    [EnableCors(origins: "http://auto-parts.azurewebsites.net/", headers: "*", methods: "*")]
        public class ProductListController : ApiController
        {
            
            public List<Product> Get()
            {
                string connectionString = "Server=tcp:autopartserver.database.windows.net,1433;Database=Autoparts;User ID=adarshjaya12@autopartserver;Password=Ad9940114541;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30";
                string command = "Select * from products";
                SqlDataReader productDataReader;
                Product product;
                List<Product> productList;
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    SqlCommand cmd = new SqlCommand(command, conn);
                    conn.Open();
                    productDataReader = cmd.ExecuteReader();
                    productList = new List<Product>();
                    if (productDataReader.HasRows)
                    {
                        while (productDataReader.Read())
                        {
                            product = new Product();
                            product.PID = Convert.ToInt16(productDataReader["Pid"]);
                            product.ProductName = productDataReader["ProductName"].ToString();
                            product.ProductManufacture = productDataReader["ProductManufacture"].ToString();
                            product.ProductPrice = Convert.ToDouble(productDataReader["ProductPrice"]);
                            product.ProductLocation = productDataReader["ProductLocation"].ToString();
                            product.ProductImage = productDataReader["ProductImage"].ToString();
                            product.ProductDescription = productDataReader["ProductDescription"].ToString();
                            productList.Add(product);
                        }
                        return productList;
                   } 
                }
                return null;
            }
        }

     

    WebAPI Config

    var cors = new EnableCorsAttribute("*", "*", "*");
                config.EnableCors(cors);
                // Web API configuration and services
                //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
                var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
                config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);

    aspx

     

        <div>
             <p id="displayText"></p>
             <button name="button" onclick="onChange">Hello</button>
        </div>
        </form>
        <script>
                  
            function onChange()
            {
                var displayText =  document.getElementById("displayText");
    
                if ("withCredentials" in xhr) {
                    var userName = document.getElementById("TextBox1").value;
                    xhr.open('GET', 'http://autopart20160514124007.azurewebsites.net/api/ProductList/', true);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            if (xhr.status == 200)
                                displayText.innerHTML = xhr.responseText;
                            else
                                alert("Not working");
                            }
                            else {
                                alert("Oops");
                            }
                        }
                    };
                    xhr.send();
                }
          
           
    
        </script>

     

    Saturday, May 14, 2016 6:13 AM

Answers

All replies

  • User36583972 posted

    Hi adarshjaya13

    Browser security prevents a web page from making AJAX requests to another domain. You can enable Cross-Origin Requests in your Web API application. You can refer the following tutorials.

    1: Enabling Cross-Origin Requests in ASP.NET Web API 2:

    http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

    2: How to use CORS with ASP.NET Web API 2.0:

    http://tostring.it/2014/03/04/how-to-use-CORS-with-ASPNET-WebAPI-2/

    You could also share us more relevant code and an error message to help us reproduce the problem.

    Best Regards,

    Yohann Lu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, May 16, 2016 5:42 AM
  • User-1636183269 posted

    I assume you are using IIS 7. Please set in web.config.

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
     <system.webServer>
       <httpProtocol>
         <customHeaders>
           <add name="Access-Control-Allow-Origin" value="*" />
         </customHeaders>
       </httpProtocol>
     </system.webServer>
    </configuration>
    Monday, May 16, 2016 6:01 AM
  • User-1596463 posted

    since you are specified

    [EnableCors(origins: "http://auto-parts.azurewebsites.net/", headers: "*", methods: "*")]

    That means, you can access this api on the page domain "http://auto-parts.azurewebsites.net/".

    If you want to access from any cross domain then put it as

    [EnableCors(origins: "*", headers: "*", methods: "*")]

    Monday, May 16, 2016 6:12 AM