jquery 如何使用www.example.com设置.asmx Web服务启用跨来源Asp.net

dauxcl2d  于 2023-02-15  发布在  jQuery
关注(0)|答案(3)|浏览(117)

我的Web服务代码是

[WebMethod]
     public List<test> GetMachineData_List(string prefix, int person_id)
     {
         using (var db = new TestDB())
         {
             List<test> list = db.Fetch<test>("select id,name from machine_data_collection mc where mc.id=@0 and name like '%" + prefix + "%'", person_id);
             return list.ToList();
         }
     }

我的jquery Ajax调用是

$("#textbx").autocomplete(
            {
                source: function (request, response) {
                 $.ajax({
                        url: 'http://localhost:4787/ws/webservice.asmx/GetMachineData_List',
                        data: { prefix: request.term.toString() ,person_id:1},
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        success: function (data) {
                            var jsonArray;
                            try {
                                jsonArray = $.parseJSON(data.d); // using jQuery
                            } catch (e) {
                                jsonArray = data.d; // using jQuery

                            }
                            response($.map(jsonArray, function (item) {
                                return {
                                    id: item.id,
                                    value: item.Name

                                };
                            }));

                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            var msg = XMLHttpRequest.responseJSON.d;
                            if (msg == undefined) {
                                alert( "Something went wrong !!" + errorThrown);
                            } else {
                                alert( "Error"+ msg);
                            }
                        }

                    });
                },
                minLength: 2,
                select: function (event, ui) {
                    var idControl = this.dataset.bindcontrol;
                    try {
                        alert(ui.item.id);

                    }
                    catch (ex) {
                        alert( "Oops .. Something happend unexpected !! .. Please redo ");
                    }
                }
            }

    );

我在web中启用了跨源。配置代码是

<system.webServer>
    <httpProtocol>
      <customHeaders>
          <add name="Access-Control-Allow-Origin" value="http://localhost:21702/" />
          <add name="Access-Control-Allow-Headers" value="X-AspNet-Version,X-Powered-By,Date,Server,Accept,Accept-Encoding,Accept-Language,Cache-Control,Connection,Content-Length,Content-Type,Host,Origin,Pragma,Referer,User-Agent" />
          <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
          <add name="Access-Control-Max-Age" value="1000" />
          <add name="Access-Control-Allow-Credentials" value="true" />
        </customHeaders>
    </httpProtocol>
  </system.webServer>

更改文本框中的文本时出错。来自Ajax调用的错误消息为:
XMLHttpRequest无法加载http://localhost:4787/ws/webservice.asmx/GetMachineData_List。对预检请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头。因此不允许访问源"http://localhost:21702"。响应具有HTTP状态代码500。

00jrzges

00jrzges1#

Web.config文件中添加以下代码片段:

<system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
   </webServices>
 </system.web>
 .............
..............
 <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Headers" value="accept, content-type" />
        <add name="Access-Control-Allow-Origin" value="http://localhost:4200"/>
        <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" /> 
        **...(add additional add names and values when you need).......**
      </customHeaders>
    </httpProtocol>
  </system.webServer>

在我的例子<add name="Access-Control-Allow-Origin" value="http://localhost:4200"/>中,Web服务消费者应用程序(Angular)的基本URL是http://localhost:4200
你必须在那个特定的地方提到你的基本网址。

m528fe3b

m528fe3b2#

尝试在你的json调用中使用jsonp。

$("#textbx").autocomplete(
        {
            source: function (request, response) {
             $.ajax({
                    url: 'http://localhost:4787/ws/webservice.asmx/GetMachineData_List',
                    data: { prefix: request.term.toString() ,person_id:1},
                    dataType: "jsonp",
yc0p9oo0

yc0p9oo03#

感谢我的名字this article solved it for me的评论
我使用的是旧的ASMX Web服务和新的Web API端点的组合。
我使用web.config的组合来指定CORS:

<customHeaders>
        <add name="Access-Control-Allow-Headers" value="accept, content-type" />
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Methods" value="POST, GET, OPTIONS" />
        <remove name="X-Frame-Options"/>
      </customHeaders>

然后是Global.asax中用于OPTIONS印前检查的处理程序:

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }

这是从上面链接的文章中得到的,但是,由于我已经在web.config中定义了一些头,所以这里不需要它们(导致重复值)。

相关问题