SVC Web服务消耗代码而不是来自javascript

时间:2014-05-22 05:08:34

标签: asp.net json web-services wcf restful-architecture

我想从myClient项目中调用项目中的Web服务(但在相同的解决方案中)。 我在myClient项目中添加了服务引用。 当我从它后面的代码调用scf时,但是当我尝试使用JSON从JavaScript调用它时,我无法这样做。伙计们帮助。

http://someurl.com/MyWebService.svc/DoWork/”是我服务的路径

abovive url someurl是localhost的网址

此代码来自JSON客户端应用程序的a.aspx,

 $.ajax(
                 {
                     type: 'GET',
                     url: 'http://someurl.com/MyWebService.svc/DoWork/',
                     contentType: "application/json; charset=utf-8",
                     data: "{}",
                     dataType: "json",
                     error: function (jqXHR, textStatus, errorThrown) {
                         alert(errorThrown);
                         alert(jqXHR.responseText);
                     },
                     success: function (data) {
                         alert(data);
                     }

                 });

来自背后的代码

string postData = "http://someurl.com/MyWebService.svc/DoWork/";
            int timeout = 10;
            //string dwml = string.Empty;
            //MyServiceReference.MyWebServiceClient ms = new MyServiceReference.MyWebServiceClient();
            //dwml = ms.DoWork();
            //System.Net.WebClient webClient = new System.Net.WebClient();
            //dwml = webClient.DownloadString(serviceURL);
            //Response.Write(dwml);

            HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(postData);
            // Set the Method property of the request to POST.
            webRequest.Headers.Clear();
            webRequest.AllowAutoRedirect = true;
            webRequest.Timeout = 1000 * timeout;
            webRequest.PreAuthenticate = true;
            webRequest.ContentType = "application / x - www - form - urlencoded";
            webRequest.Credentials = CredentialCache.DefaultCredentials;
            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
            webRequest.Timeout = 150000;
            // Create POST data and convert it to a byte array.

            WebResponse webResponse = null;
            StreamReader objSR;
            System.Text.Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            Stream objStream;
            string sResponse;

            webResponse = (HttpWebResponse)webRequest.GetResponse();
            objStream = webResponse.GetResponseStream();
            objSR = new StreamReader(objStream, encode, true);
            //<<sResponse doesn't contain Unicode char values>>
            sResponse = objSR.ReadToEnd();
            Response.Write(sResponse);  // OR Response.write(HttpUtility.HtmlEncode(sResponse)) 

3 个答案:

答案 0 :(得分:1)

这是第二个问题(仅由我提出),只有我自己已经回答或评论过。我从堆栈溢出旧问题得到ans 4这个问题 Basic example of using .ajax() with JSONP?

问题是通过AJAX不允许跨域Web服务调用。 我遇到了JSONP的新概念,感觉很棒!

但我期待Stack快速回复其他成员。

每次朋友我都无法自救!

答案 1 :(得分:1)

RESTclient的不同解决方案中从JSONP调用WCF服务:

在这里,我提出了另一个有效的解决方案,在不使用RESTclient 的情况下,在不同的解决方案 中调用来自JSONP的WCF服务,即启用 CORS 服务(跨源资源共享)策略。 我们都必须尝试过:

在服务项目的Access-Control-Allow-Origin文件中添加标题web-config

web-config中的代码:

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
    <add name="Access-Control-Max-Age" value="1728000" />
  </customHeaders>
</httpProtocol>

但无论如何,那对我来说没有用!

所以,还有另一种实现相同的方法,就是在服务项目中创建Global.asax 并将此代码添加到Global.asax.cs

Global.asax.cs中的代码:

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

您可以继续从RESTclient解决方案到WCF服务的常规AJAX调用:

示例AJAX:

$(document).ready(function () {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "http://localhost:51058/Service1.svc/GetData",
            dataType: 'json',
            success: function (data) {
                //do success part here
                alert(data);
            },
            error: function (e) {
                alert(e.message);
            }
        });
    });

最好的部分是,无需在RESTclient项目解决方案中进行任何修改。

答案 2 :(得分:0)

这里我到目前为止已经尝试了

SVC代码文件service1.svc.cs

using System;

namespace TestConnection
{
    public class Service1 : IService1
    {
        public string GetData()
        {
            return string.Format("You entered: {0}", "Success");
        }
    }
}

JavaScript函数:

   <script type="text/javascript">
    $(document).ready(function () {
        var text;
        $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: 'Service1.svc/GetData', /*you .svc address : 'http://someurl.com/MyWebService.svc/DoWork/'*/
            dataType: "json",
            async: false,
            success: function (a) {
                var response = $.parseJSON(a);
                text = response.Table[0];
                alert(text);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert('Failure');
            }
        });
    });
</script>

您可能已经尝试过的所有上述代码,一些重要的注意事项是:

1。,因为WCF .svc适用于 Representational State Transfer (REST),您必须在service1.svc标记文件中明确提及数据获取请求,< / p>

[OperationContract]
[WebGet()]
//You can use below attributes to make necessary modifications
        //RequestFormat = WebMessageFormat.Json,
        //ResponseFormat = WebMessageFormat.Json,
        //BodyStyle = WebMessageBodyStyle.Bare,
        //UriTemplate= "GetData"
        //)]
    string GetData();

要使用WebGet,您需要将库System.ServiceModel.Web添加到服务项目中。

如果您对基本设置有疑问,

Web.Config中:

<system.serviceModel>
<behaviors>
  <serviceBehaviors>
    <behavior name="">
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="false" />
    </behavior>
  </serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
  multipleSiteBindingsEnabled="true" />
<bindings>
  <basicHttpBinding>
    <binding name="BasicHttpBinding_IMathService" />
  </basicHttpBinding>
</bindings>
</system.serviceModel>

注意:这不适用于跨域,如果您需要,请回答Here