SVC Web service consuming from code behind but not from javascript

只愿长相守 提交于 2019-12-08 13:28:51

问题


I want to call web service in project (but in same solution) from myClient project. I have added service reference in myClient project. When I call scf from code behind it, works but when I try to call it from JavaScript using JSON, I am unable to do so. Guys pls help.

"http://someurl.com/MyWebService.svc/DoWork/" is path of my Service

abovive url someurl is url of localhost

This code is from a.aspx of client application of JSON,

 $.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);
                     }

                 });

From Code behind

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)) 

回答1:


Guys this immediate second question (both asked by me only) which only myself has answered or commented. I got ans 4 this from stack overflows old question
Basic example of using .ajax() with JSONP?

Issue was with cross domain web-service call is not allowed through AJAX. I came across new concept of JSONP, wow feeling great!

But I was expecting quick reply from Stack overflows other members.

I will not be able to rescue myself every time friends!




回答2:


calling WCF service from RESTclient in different solution without JSONP:

Here I came up with another working solution for, calling WCF service from RESTclient in different solution without using JSONP i.e. Enabling CORS of service (Cross Origin Resource Sharing) policy. We all must have tried:

Adding Header Access-Control-Allow-Origin in web-config file of Service Project,

Code in 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>

but anyhow, that didn't worked out for me!

So, there is another way to achieve the same, is to Create a Global.asax in Service Project and Add this code to the Global.asax.cs:

Code in 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();
        }
    }

And you can continue with your regular AJAX call from RESTclient solution to WCF service:

Sample 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);
            }
        });
    });

The best part is, no need to do any modifications in RESTclient project solution.




回答3:


here I have tried so far

SVC code file service1.svc.cs :

using System;

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

JavaScript function:

   <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>

All above code you might have tried, some important note to get this worked is:

1. as WCF .svc works on Representational State Transfer (REST), you have to explicitly mention data get request in service1.svc Markup file,

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

To use WebGet,you will need to add library System.ServiceModel.Web to your service Project.

And if you have issues with basic settings then,

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>

NOTE: This will not work for cross domain, if you want that, its answered Here.



来源:https://stackoverflow.com/questions/23798224/svc-web-service-consuming-from-code-behind-but-not-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!