Showing posts with label REST. Show all posts
Showing posts with label REST. Show all posts

Saturday, July 11, 2020

Querying Entities' Properties in Web API OData RESTful with ODataController

In this article we enable the Querying of an Entity's Property in an Web API OData RESTful service with ODataController.
Our task here is to perform OData protocol queries in order to get the value of some Entity's property, the following query for example :
http://localhost:6954/Odata/Notes(10)/Body/$value


When developing an ODataController to create an OData Web API, having configurated the application properly, as in the previous tutorial, you get automatically support for the most common OData protocol's queries. You can then query the OData Web API using $metadata, $value, $select, $top, $skip, $filter and even $expand , to get the JSON response:
http://localhost:6954/OData/$metadata#Notes :

              /Odata/Notes?$filter=From eq 'Fry'





http://localhost:6954/OData/Notes?$skip=2&$top=10

http://localhost:6954/OData/Notes?$select=Body

There are some conventions to follow when developing an ODataController:

1) the controller's name must be the entity name, the root of the resource path:

      /Notes(10)      implies that the Web API will look for a controller named NotesController (case sensitive)

2) the Action name for fetching an Entity's property will be set according to the Entity type and the Property name, as follows:

  /Notes(10)/Body       
      means that the Web API will look for an Action method named GetBodyFromNote()

All this conventions can be found in the Microsoft Asp.Net official site.
Let's say we have an Entity named "Note" with some property called "Body" : we want to call the OData HTTP service with this URI:
      http://localhost:6954/Odata/Notes(10)/Body/

So, according to the OData protocol specification, we need an Action method named GetBodyFromNote(), marked with the attribute "[EnableQuery]" , which returns the required property from the Entity:


(COPY-PASTE THIS CODE) : 


 [EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
        public string GetBodyFromNote([FromODataUri]int key)
        {
            IEnumerable<Note> data = Repository.GetAll();
            var note = data.Where(n => n.ID == key) .SingleOrDefault();
            return note.Body ;
        }



Build & run the application, and type the URI to fetch the required property in JSON format:

http://localhost:6954/Odata/Notes(10)/Body/
Also, we can request ONLY the $value of the property:

http://localhost:6954/Odata/Notes(10)/Body/$value
That's all
In this post we've seen how we perform Querying Entities' Properties in Web API OData RESTful with ODataController. 

Enjoy programming.....
    By Carmel Shvartzman
כתב: כרמל שוורצמן

Saturday, January 30, 2016

Step by step how to send an HTTP DELETE Request to an RESTful WCF Service using Fiddler

In this tutorial we'll learn how to create an HTTP DELETE Request to an RESTful WCF application using Fiddler
We'll use Fiddler for testing purposes of a RESTful WCF application, sending  HTTP DELETE requests. We'll start with a WCF application,  and we'll remove an entry using Fiddler, showing as follows :





First of all, we have to download the FREE Fiddler tool from this web site :



Now check the settings of the Operation Contract at the WCF Service Contract, in order to provide exactly what it is expected:



The WebInvoke is set to handle the DELETE HTTP method, and the request format is supposed to be JSON, the same as the response format. So, we'll send what the WCF wants.
Open Fiddler and find the "Composer" option:




Then type in the WCF service URL and select "DELETE" HTTP method from the list. Set the request Headers as follows: (the Content-Length  will be filled by Fiddler for you):



Fill the Request Body, and take care to fill the ID of the record to remove. The rest of fields is just optional.

Press the "EXECUTE" button  to send the request. If you set a breakpoint inside the WCF operation, you'll see the following in action :


As you see, WCF succeeded at identifying inside the JSON the ID to erase.
Then the response is sent to Fiddler, with a "true" value, because everything went fine:


And the database shows the deleted value:



If you want to see the RESTful WCF that we're using here, see this tutorial.

That's all.... 
In this tutorial we've seen how to send an HTTP DELETE Request to an RESTful WCF service using Fiddler. 
Happy programming.....
      By Carmel Shvartzman
כתב: כרמל שוורצמן








Wednesday, November 19, 2014

How to expose a WCF Service through many endpoints and multiple bindings

  
In this post we'll explore how to expose one single WCF Service through many  endpoints and multiple bindings. We'll have only one C# WCF code, and we'll make it implement several interfaces in order to expose several endpoints with many different bindings. Technically, we'll create several WCF services via creating several interfaces, but the C# class implementing them will be running the SAME CODE. We'll enable that unique C# class code to handle both Soap and HTTP requests, proceeding from backends calls, from jQuery Ajax calls, and from standard HTTP web calls. Some calls will be made programmatically in C# from some Application Back-End . Other, REST calls, will proceed from Ajax or from regular web calls. But ALL requests will be handled by the SAME C# service class.

How to expose a WCF Service through many endpoints and multiple bindings


Another interesting feature of this exercise will be, we are not creating a WCF Application, but adding a WCF Web Service to an existing MVC application.
The schema of our WCF app will be as follows : one unique C# Class, which implements two Interfaces as Services Contracts, finally exposed through three Endpoints:
How to expose a WCF Service through many endpoints and multiple bindings



One of the Endpoints will handle Soap calls, one HTTP web calls, and another one Ajax HTTP web calls. The first one will use an basicHttpBinding, and the former two, an webHttpBinding.

The WCF service we are building will handle HTTP requests based on the REST (REpresentational State Transfer) architecture, designed by Dr. Fielding at 2000. Our WCF sample will receive HTTP requests depending what it intends to do:

1) CREATE an item :     HTTP "POST" request
2) RETRIEVE  an item : HTTP "GET" request
3) RETRIEVE  ALL items : HTTP "GET" request

We'll want to create an WCF Web Service with CRUD functionality, which fetches and persists all data proceeding from a RESTful Web Service, based on a Model as follows:


Step 1 - Add a WCF Service to your application



Step 2 - Write the C# code for the WCF Service


[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class BlogService : IBlogService,IBlogService1
    {
        public string GetBlogs()
        {
            Models.BlogEntities ctx = new Models.BlogEntities();
            ctx.Configuration.ProxyCreationEnabled = false;
            List<Blog> data = ctx.Blogs.ToList();

            return new JavaScriptSerializer().Serialize(data);
        }

        public string GetBlog(string Id)
        {
            Models.BlogEntities ctx = new Models.BlogEntities();
            ctx.Configuration.ProxyCreationEnabled = false;
            int id = Convert.ToInt32(Id);
            Blog data = ctx.Blogs.Where(b => b.BlogID == id).FirstOrDefault();

            return new JavaScriptSerializer().Serialize(data);
        }

        public string CreatePost(Blog post)
        {
            Blog responsePost = post;
            return new JavaScriptSerializer().Serialize(responsePost);
        }
    }

Why do we create first the service implementation and after that the interfaces? Because we know exactly what our class is supposed to do, but only later we'll decide how many Service Contracts we'll need.

Step 3 - Create the C# interfaces as Service Contracts

In this example, we create two Service Contracts through two Interfaces: the first one look this way:



[ServiceContract]
    public interface IBlogService
    {
        [OperationContract]
        [WebGet]
        string GetBlogs();
        [OperationContract]
        [WebGet]
        string GetBlog(string Id);
        [WebInvoke(Method = "POST")]
        [OperationContract]
        string CreatePost(Blog post);
    }

The second one is similar but has the Operation Contracts names changed:


[ServiceContract]
    public interface IBlogService1
    {
        [OperationContract(Name = "GetBlogsSoapREST")]
        [WebGet]
        string GetBlogs();
        [OperationContract(Name = "GetBlogSoapREST")]
        [WebGet(UriTemplate="GetBlog1/{id}")]
        string GetBlog(string Id);
        [WebInvoke(Method = "POST")]
        [OperationContract(Name = "CreatePostSoapREST")]
        string CreatePost(Blog post);
    }

Then, we make our Service Class to implement the Interfaces:




Step 4 - Declare the WCF Service & its Endpoints

At the web.config, declare the service with its service behavior:



This service behavior states that the service metadata can be fetched , using the declaration:

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

Also we want that , at this development stage of our application, the errors could be view by us:
includeExceptionDetailInFaults="true"

Now we create three Endpoints:


 <service name="WCF_RESTful.BlogService" 
               behaviorConfiguration="MultipleInterfacesAndEndpointsSvc" >
       <endpoint 
         address="RESTfulAjax" 
         behaviorConfiguration="RESTfulAjaxBehavior"  
         binding="webHttpBinding" 
         contract="WCF_RESTful.IBlogService" />
        <endpoint 
          address="RESTfulNoAjax" 
          behaviorConfiguration="RESTfulNoAjaxBehavior"
          binding="webHttpBinding" 
          contract="WCF_RESTful.IBlogService1" />
        <endpoint 
          address="SoapEndpoint"  
          binding="basicHttpBinding" 
          contract="WCF_RESTful.IBlogService1" />
      </service>

The first two are for REST calls, that's why we use webHttpBinding. Each one exposes a different Service Contract (interface).
The last is for Soap calls, and therefore uses basicHttpBinding.
Now , to handle regular HTTP REST calls, we need to bind a "webHttp" behavior to the Endpoint:



 <behavior  name="RESTfulNoAjaxBehavior" >
          <webHttp />
        </behavior>

And to handle Ajax web calls, we declare another behavior using "enableWebScript", which also includes the "webHttp" directive:

Step 5 - Routing

Finally, reroute the path since we are inside an MVC application:

routes.IgnoreRoute("BlogService.svc/{*pathInfo}");


Build & run, and let's call our WCF from :
1) Soap request: we create a service reference in some MVC application, and discover our WCF with its methods:

The WSDL schema appears as this:



Now, just build the back end client Proxy and use the service.

2) Web HTTP REST request: XML response : 


And for getting just one record :



As you see, the response is given in XML format. Notice that we needed to call an "GetBlog1" method: that's because we defined an UriTemplate at the Operation Contract , and because of the format "GetBlog1/{id}" we don't need to specify the "GetBlog1?id=4" argument: 


3) Ajax REST HTTP request: Json response : 



Here, the response is Json. And to get only one record:




That's all!! 
In this tutorial we've learn How to expose a WCF Service through many endpoints and multiple bindings.  

Happy programming.....
      By Carmel Shvartzman
כתב: כרמל שוורצמן

Friday, September 19, 2014

Create an Ajax Web Client for OData Web API RESTful Service - HTTP-DELETE JSON


In this article we'll design a web client for deleting a record by sending an HTTP DELETE call via Ajax to an Web API OData RESTful service implemented using an ODataController. The design will be made applying Twitter Bootstrap.

This post uses an OData Web API  designed in a previous Web API ODataController tutorial. The  Twitter Bootstrap's setup can be learned in this post. Also, the OData protocol for the MVC Web API with ODataControllers can be seen at the Microsoft Asp.Net site

We want to send an Ajax HTTP  DELETE request to the OData HTTP Web API service to delete an item, using this screen :
Ajax Web Client for OData Web API RESTful Service - HTTP-DELETE JSON



First create the MVC application as an empty web site:




Import the style and the script files  (you can learn the Twitter Bootstrap installing instructions here)


Take a look at the Web API ODataController class, to see the Delete( int  ) method that we're using:



The Delete() action method requires an integer ID , returning an  IHttpActionResult object.

Ajax Web Client for OData Web API RESTful Service - HTTP-DELETE JSON



Create a new web client for the OData service:


Add the references to the Twitter Bootstrap:



Then we add a DOM element for selecting the KEY  of the record to delete:

Next, we create all the input tags for showing the record's details:


This is the markup to copy-paste:

   <div class="panel panel-default">            <div class="panel-heading row">                <div class="text-muted col-xs-6">                    <h2>Message Details</h2>                </div>                <div class="text-muted col-xs-3">                    <div class="editor-label">                        ID                    </div>                    <div class="editor-field">                        <input type="number" name="ID" value="3" class="form-control" />                    </div>                </div>
            </div>            <div class="panel-body text-muted">                <div class="row">                    <div class="col-xs-6">                        <div class="editor-label">                            To                        </div>                        <div class="editor-field">                            <input type="text" name="To" class="form-control" />                        </div>                    </div>                    <div class="col-xs-6">                        <div class="editor-label">                            From                        </div>                        <div class="editor-field">                            <input type="text" name="From" class="form-control" />
                        </div>                    </div>                    <div class="col-xs-12">                        <div class="editor-label">                            Heading                        </div>                        <div class="editor-field">                            <input type="text" name="Heading" class="form-control" />
                        </div>                    </div>                    <div class="col-xs-12">                        <div class="editor-label">                            Body
                        </div>                        <div class="editor-field">                            <input type="text" name="Body" class="form-control" />
                        </div>                    </div>                    <div class="center">                        <div class="center">                            <br />                            <div class="row">                                <div class="col-lg-6">                                    <input class="btn btn-sm btn-default" value="See Message Details" />                                </div>                                <div class="col-lg-6">                                    <input class="btn btn-sm btn-default" value="Delete Message" />                                </div>                            </div>                        </div>                        <br />                        <div class="alert alert-success message"></div>                        <div class="alert alert-danger error"></div>                    </div>                </div>            </div>        </div>    </div>  





After the HTML, write the script, opening with the references to the jQuery and the Bootstrap  files:

When the "Details" button is clicked, the web page send an Ajax call containing the key of the item (inside the URI )   :



If the response was an 200 - OK, we show the item; in case of error, we display a message:


This is the code for the script:

  <script src="Scripts/jquery-2.1.1.js"></script>    <script src="Scripts/bootstrap.js"></script>    <script>        $(function () {            $("div.message").css("display", "none");            $("div.error").css("display", "none");
            $("input.btn[value*=Details]").click(function () {
                var id = $("input[name=ID]").val();                $.ajax({                    url: "http://localhost:6954/OData/Notes(" + id + ")",                    type: "GET",                    data: id,                    dataType: "json",                    contentType: "application/json",                    beforeSend: function (data) {                        //alert(id);                    },                    success: function (data) {                        var note = data;                        $("div.error").css("display", "none");                        $("div.message").css("display", "block");                        $("div.message").text("The Message with ID = " + id + " was retrieved successfully!!!");                        $("input[name=To]").val(note.To);                        $("input[name=From]").val(note.From);                        $("input[name=Heading]").val(note.Heading);                        $("input[name=Body]").val(note.Body);                    },                    error: function (msg) {                        var oError = JSON.parse(msg.responseText);                        fnError("Error : " + oError.error.innererror.message, id);                    }                })            });
            function fnError(msg, id) {                $("div.message").css("display", "none");                $("div.error").html("The message with ID = " + id + " does not exist. Try again.");                $("div.error").css("display", "block");            }



The method inside the ODataController renders the required item:



Now, we need an $.ajax() method to DELETE the selected record, using the HTTP DELETE verb:



This is the code for copy-paste in your project:

    $("input.btn[value*=Delete]").on("click", function () {
                var id = $("input.form-control[name*=ID]").val();
                 
                $.ajax({
                    url: "http://localhost:6954/OData/Notes(" + id + ")",
                    type: "DELETE",
                    data: id,
                    contentType: "application/json",
                    dataType: "json",
                    success: function (data) {
                        $("div.error").html(data.responseText); 
                    },
                    error: function (msg) {                                                
                         
                        if (msg.status == "410") {
                            $("div.message").text('The item was successfuly deleted.');
                        }
                    }
                });
            });
        })
    </script>


Here, we send an Ajax HTTP DELETE request to the OData Web API web service. Notice that the response for an OK has been defined as code 410 ("Gone"), that means that the Ajax request receives an ERROR by response, so we handle it in the error callback of the $.ajax() method!!!!!!

Run the application: the User retrieves the item's details, and clicks the second button, deleting the record:





The Ajax request reaches the OData Web API service, which we built in a previous article about   OData v4.0 WebAPI  updating  (HTTP PUT & HTTP PATCH) that can be found here.
This is the Delete() method which handles the HTTP DELETE request at the OData service:



As you see, we just delete the item, sending an "Gone" status message. Remember that "Gone" is the error 410, therefore we handle it at client side at the error callback.

That's all!!!!

In this article we've seen step by step how to create a web client which deletes a record by sending an HTTP DELETE Ajax request to an WebAPI OData RESTful service implemented with an MVC ODataController.
Enjoy OData Web API  !!!!

By Carmel Shvartzman

עריכה: כרמל שוורצמן