使用带有CORS策略的Ajax调用问题来调用IIS发布的Web API

时间:2019-03-20 13:04:51

标签: ajax asp.net-web-api

我使用客户端按钮上的normal(.aspx)页面开发了一个示例Web应用程序,单击下面为Web API调用编写的函数

function AddEmp() {  

        var Emp = {};  
        Emp.FirstName = $("#txtFirstName").val();  
        Emp.LastName = $("#txtLastName").val();           
        Emp.Company = $("#txtCompany").val();    


        $.ajax({
            url: 'http://localhost:55339/api/Emp/AddEmployees',
            type: 'POST',
            contentType: 'application/json;charset=utf-8',  
            data: JSON.stringify(Emp),
            dataType: 'json',
            success: function (response) {  
                alert(response);           
            },  
            error: function (x, e) {
            }  
        });   
    }       

在Web API中,将Emp控制器以下功能代码写入数据库中。

public string AddEmployees(Employee Emp)
    {
        connection();
        com = new SqlCommand("InsertData", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.AddWithValue("@FName", Emp.FirstName);
        com.Parameters.AddWithValue("@Lname", Emp.LastName);
        com.Parameters.AddWithValue("@Compnay", Emp.Company);
        con.Open();
        int i = com.ExecuteNonQuery();
        con.Close();
 }

单击按钮后,我在检查器中收到以下错误

Access to XMLHttpRequest at 'http://localhost:55339/api/Emp/AddEmployees' from origin 'http://localhost:2252'

 has been blocked by CORS policy: Response to preflight request doesn't pass access control 

check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我尝试了以下选项

crossDomain: true,

headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true,
            },

什么都行不通。如何解决此问题。

0 个答案:

没有答案