从JavaScript CORS ASP.NET Web服务 [英] CORS ASP.NET webservice from javascript

查看:147
本文介绍了从JavaScript CORS ASP.NET Web服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何让一个普通的HTML页面(使用JavaScript)从中我使用Asp.Net在Visual Studio中创建一个WebService获取数据。我的最后一个项目都将有一个网域的互联网服务和结果将需要由HTML页面在另一个域接收。

我有一个真的很难搞清楚如何建立web服务,使我的网页可以谈论它。

我一直努力遵循:

http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

阿贾克斯JQuery的没有?

和这里的视频:<一href=\"http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-and-call-a-simple-web-service-in-aspnet\" rel=\"nofollow\">http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-and-call-a-simple-web-service-in-aspnet

但我似乎无法制定出扭结。当我尝试加载使用Firefox没什么页面返回。我几乎可以肯定,这个问题与我试图使用URL做的,但我不知道够不够弄清楚它应该是什么。

什么是获得从功能HelloWorld2使用JavaScript返回值的最佳方式?

先谢谢了。

WebService的

 使用系统;
使用System.Collections.Generic;
使用System.Linq的;
使用的System.Web;
使用System.Web.Services;命名空间StoneSoupMockup
{
    ///&LT;总结&gt;
    ///对WebService的摘要说明
    ///&LT; /总结&gt;
    [WebService的空间(namespace =htt​​p://SomeDumbUniqueID.org/,说明=这是石头汤示例服务。NAME =则将MyService)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)
    [System.ComponentModel.ToolboxItem(假)]
    //要允许此Web服务从脚本调用,使用ASP.NET AJAX,取消注释以下行。
     [System.Web.Script.Services.ScriptService]
    公共类服务1:System.Web.Services.WebService
    {
        [的WebMethod]
        公共字符串的HelloWorld()
        {
            返回的Hello World;
        }        [的WebMethod]
        公共字符串HelloWorld2(字符串的东西)
        {
            回归你好+的东西;
        }
    }
}

我添加访问控制头的httpProtocol在我的web服务项目像这样

的Web.config

 &LT; system.webServer&GT;
     &LT;模块runAllManagedModulesForAllRequests =真/&GT;
      &LT; httpProtocol&GT;
          &LT; customHeaders&GT;
              &LT;添加名称=访问控制允许来源VALUE =*/&GT;
              &LT;添加名称=访问控制 - 允许 - 头VALUE =Content-Type的/&GT;
          &LT; / customHeaders&GT;
      &LT; / httpProtocol&GT;
  &LT; /system.webServer>

JavaScript的:

  // WebServices.js
功能myAjax(){
     VAR XMLHTTP =新XMLHtt prequest();     //我真的不知道这个网址。这是Visual Studio中具有用于
     //当我测试我的应用程序的网址
     VAR URL =HTTP://本地主机:62033 / Service1.asmx的/ HelloWorld2
     // VAR参数==第奥巴马和放大器;最后=奥巴马;
     VAR参数=东西=提米
     xmlHttp.open(POST,网址,真实);     //黑魔法款
     xmlHttp.setRequestHeader(内容类型,应用程序/ x-WWW的形式urlen codeD);
     xmlHttp.setRequestHeader(内容长度,parameters.length);
     xmlHttp.setRequestHeader(连接,关闭);     xmlHttp.onreadystatechange =功能(){
      如果(xmlHttp.readyState == 4和&放大器; xmlHttp.status == 200){
       的document.getElementById('ajaxDump')的innerHTML + = xmlHttp.responseText +。&LT; BR /&gt;中;
      }
     }     xmlHttp.send(参数);
}

HTML code:

 &LT; HTML和GT;
    &LT; HEAD&GT;
        &LT;元CONTENT =text / html的;字符集= UTF-8HTTP的当量=Content-Type的&GT;
        &LT;元CONTENT =UTF-8HTTP的当量=编码&GT;        &LT;脚本SRC =WebServices.js类型=文/ JavaScript的'&GT;&LT; / SCRIPT&GT;
    &LT; /头&GT;
    &LT;身体GT;    &LT; D​​IV ID =resultdiv&GT;&LT; / DIV&GT;
    &LT;脚本类型=文/ JavaScript的'&GT;
        myAjax();
    &LT; / SCRIPT&GT;    &LT; /身体GT;
&LT; / HTML&GT;


解决方案

您需要一个CORS图书馆作为服务的一部分。如果你现在需要它,再看看进入Thinktecture IdentityModel库:

<一个href=\"http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/\" rel=\"nofollow\">http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/

否则等待的WebAPI的下一个版本:

<一个href=\"http://brockallen.com/2013/03/13/cors-open-source-contribution-to-asp-net-and-system-web-cors/\" rel=\"nofollow\">http://brockallen.com/2013/03/13/cors-open-source-contribution-to-asp-net-and-system-web-cors/

http://aspnetwebstack.$c$cplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API

I'm trying to figure out how to make a regular html page (with javascript) get data from a WebService which I created in Visual Studio using Asp.Net. My final project is going to have the WebService hosted in one domain and the results will need to be received by the html page in another domain.

I'm having a really hard time figuring out how to set up the webservice such that my page can talk to it.

I've been trying to follow:

http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server

Ajax Without JQuery?

and the video here: http://www.asp.net/web-forms/videos/how-do-i/how-do-i-create-and-call-a-simple-web-service-in-aspnet

but I can't seem to work out the kinks. When I try to load the page using Firefox nothing is returned. I'm almost positive that the problem has to do with the URL I'm trying to use, but I don't know enough to figure out what it should be.

What is the best way to get the return value from the function HelloWorld2 using javascript?

Thanks in advance.

WebService

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace StoneSoupMockup
{
    /// <summary>
    /// Summary description for WebService
    /// </summary>
    [WebService(Namespace = "http://SomeDumbUniqueID.org/", Description="This is a sample service for Stone Soup.", Name="MyService")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
     [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public string HelloWorld2(string something)
        {
            return "Hello " + something;
        }
    }
}

I added access control headers to the httpProtocol in the web.config of my web services project like this

<system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
      <httpProtocol>
          <customHeaders>
              <add name="Access-Control-Allow-Origin" value="*"/>
              <add name="Access-Control-Allow-Headers" value="Content-Type" />
          </customHeaders>
      </httpProtocol>
  </system.webServer>

JavaScript:

//WebServices.js
function myAjax() {
     var xmlHttp = new XMLHttpRequest();

     //I'm really not sure about this URL. This is what Visual Studio has for the 
     //URL when I test my app
     var url="http://localhost:62033/Service1.asmx/HelloWorld2";
     //var parameters = "first=barack&last=obama";
     var parameters = "something=timmy"
     xmlHttp.open("POST", url, true);

     //Black magic paragraph
     xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
     xmlHttp.setRequestHeader("Content-length", parameters.length);
     xmlHttp.setRequestHeader("Connection", "close");

     xmlHttp.onreadystatechange = function() {
      if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
       document.getElementById('ajaxDump').innerHTML+=xmlHttp.responseText+"<br />";
      }
     }

     xmlHttp.send(parameters);
}

HTML Code:

<html>  
    <head>  
        <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
        <meta content="utf-8" http-equiv="encoding">

        <script src="WebServices.js" type='text/javascript'></script>


    </head>
    <body>

    <div id="resultdiv"></div>


    <script type='text/javascript'>
        myAjax();   
    </script>

    </body>
</html>

解决方案

You need a CORS library as part of your service. If you need it now, then look into the Thinktecture IdentityModel library:

http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/

Otherwise wait for the next release of WebAPI:

http://brockallen.com/2013/03/13/cors-open-source-contribution-to-asp-net-and-system-web-cors/

http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API

这篇关于从JavaScript CORS ASP.NET Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆