Showing posts with label wcf. Show all posts
Showing posts with label wcf. Show all posts

jQuery ajax handle exception thrown by wcf

When we work with jQuery Ajax call to WCF, it may possible that WCF service will thow an exception. And we need to catch that exception in jquery ajax error routine. In order to show or get exception thrown by service we need to configure includeExceptionDetailInFaults="True" for in behavior like:

<serviceBehaviors>
  <behavior name="">
    <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="true" />
  </behavior>
</serviceBehaviors>

Now when jquery ajax call revices error then exception comes in resposeText as Message.But we need extract Message from responseText as responseText comes as cominations of error details. This can be done using jQuery.parseJSON like:



 .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
        });

Now to get Message part we can use r.Message. This will give you the message that is sent by exception in wcf service.


 .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
          alert("Message: " + r.Message);
        });

Code for jQuery ajax handle exception thrown by wcf

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>Jquery ajax json call to wcf service</title>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#btnClick").click(function () {
        var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
          alert("Message: " + r.Message);
          alert("StackTrace: " + r.StackTrace);
          alert("ExceptionType: " + r.ExceptionType);
          alert("ERROR" + response.d);
        });
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" id="messageinput" />
    <asp:Button ID="btnClick" runat="server" Text="Button" />
  </div>
  </form>
</body>
</html>

Note: To test example of catch exception in jquery ajax thrown by wcf service, just throw an application exception or Exception with some message like:

    [WebGet()]
    [OperationContract]
    public string GetMessage(string message)
    {
      //return "WCF" + message;
      throw  new  ApplicationException("This is exception");
    }

Configure wcf service to call in jquery ajax json

In previous post we saw how to create wcf service to be get called by jquery ajax and json. After creating wcf service we need to configure wcf service in web.config in order to make it accessible.

wcf service configuration for jquery ajax call

Configure wcf service

  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="GetJson">
          <enableWebScript />
        </behavior>
        <behavior name="PostJson">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="aspnetcontrol.Service1">
        <endpoint address="get-json"
                  binding="webHttpBinding"
                  behaviorConfiguration="GetJson"
                  contract="aspnetcontrol.Service1" />
    
        <endpoint address="post-json"
                  binding="webHttpBinding"
                  behaviorConfiguration="PostJson"
                  contract="aspnetcontrol.Service1" />
      </service>
    </services>
  </system.serviceModel>

Create wcf service to call by jquery ajax json

In this post we will see how to create wcf service in C# that we can call through jquery ajax and json. The namespaces we need in wcf service are System.ServiceModel, System.ServiceModel.Web and System.ServiceModel.Activation.

create wcf service to be called by jquery ajax json

Example- WCF service to call by jquery ajax json

using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Web;

namespace aspnetcontrol
{
  [ServiceContract(Namespace = "")]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class Service1 
  {
    [WebGet()]
    [OperationContract]
    public string GetMessage(string message)
    {
      return "WCF" + message;
    }
  }
}

Note: In above code important attributes are [ServiceContract(Namespace = "")], [OperationContract] and [WebGet()]. ServiceContract specifies that class defines service contract in application.
OperationContract specifies that a method defines and operation that is part of web service contract.
WebGet indicates service operation is logically a retrieval operation. In this way we can create wcf service to be called using jquery ajax json. In order to make service accessible we need to configure wcf service in web.config.

jQuery Ajax call to WCF service

In jQuery we can perform an asynchronous HTTP (Ajax) request. In this post we will see simple example of how jquery Ajax call to WCF service works. We can call wcf service using jquery ajax and json.

use jquery ajax to call wcf service
We can use $.ajax to call the wcf service like:
 var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response) {
          alert("ERROR"+response.d);
        });


Here in above code snippet we have set various parameters for jquery ajax call like: type: 'GET' - means request is of type GET and not POST
url: '', here we have mentioned the url of wcf service, where Service1.svc is wcf service name, get-json is address set in the web.config wcf service and GetMessage is actual method in wcf service.
data: dto is the parameter data that we need to pass to wcf service method.

Example jquery ajax call to wcf service

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>Jquery ajax json call to wcf service</title>
  <script type="text/javascript">
   $(document).ready(function () {
      $("#btnClick").click(function () {
        var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response) {
          alert("ERROR"+response.d);
        });
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" id="messageinput" />
    <asp:Button ID="btnClick" runat="server" Text="Button" />
  </div>
  </form>
</body>
</html>

In above example we can type some message in textbox and pass message to wcf service using jquery ajax call and get it in respose back.

Note: To run above example we need to create wcf service and configure wcf service endpoint in web.config file properly