⬆️ ⬇️

Calling web services and web architecture methods.net

This note describes how easy it is to call a .Net web service (written, for example, in an asp.net project) using the jQuery library. I had a little doubt about where to put this note, here or on the .Net blog, and finally decided that the topic of the note is more about jQuery and its features than the topic of .Net programming.



So, let's begin.



.Net



Performance tested on .net framework 3.5, in versions .net below 3.0, this example may not work.



The first thing you need to know the features of web services written in .net. For information, it is better to contact the source and in our case it will be ScottGu, the architect of .Net. His blog has a wonderful article “JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks”.



weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx

')

This article describes the requirements and conditions for calling methods marked with the [WebMethod] attribute that the AJAX.NET architecture also performs.



Conditions, in fact, only two:

- use only POST requests;

- the request should contain the following header

Content-Type: application / json; charset = utf-8.



Web service



First, let's write a simple web service that receives the login text and returns the boolean value of whether or not the login is in the database.

[WebMethod]

public bool CheckLogin ( string login)

{

bool result = false ;

if (login.Length> 0)

{

ORMDataContext db = ORMDataContext.GetDB ();

var user = BisORM.User.GetUser (login);

if (user! = null )

{

result = true ;

}

}

return result;

}

* This source code was highlighted with Source Code Highlighter .




As you can see, this method is very simple; it uses Linq to SQL and the generated ORM (ORMDataContext) to determine if the login passed in the database.



jQuery



There are several functions for working with ajax in jQuery, one of which just fits all our requirements. This is a function of $ .ajax. I will not dwell on the description of this function and all its parameters, this data can be easily found on the official project website in the documentation section. Define the following javascript helper function:

function ExecuteService ( params , url, callbackSuccess, callbackError)

{

$ .ajax ({

type: "POST" ,

url: url,

contentType: “application / json; charset = utf-8 " ,

dataType: “json” ,

data: params ,

success: callbackSuccess,

error: callbackError

});

} * This source code was highlighted with Source Code Highlighter .




The ExecuteService function accepts the following parameters:

- params - JSON string with parameters that must be passed to call the web service;

- url - the full address of the web service with the web method;

- callbackSuccess - the function that will be called when the web method is successful;

- callbackError - the function that will be called when an error occurs during the execution of the web method.



It should be noted that one parameter with the result of the web method in the format of a JSON string will be passed to callbackSuccess, and three parameters will be passed to the callbackError:

- a copy of the request;

- text message;

- description of the error.



As you can see, ExecuteService fulfills all the requirements for the query that .Net puts forward and which were described above: a post-request is formed, the desired value is assigned to the “contentType” header.



Using



Now, finally, let's write the code that interacts with our web service via jQuery:

function CheckLogin (input, callbackResult, callbackError)

{

var login = $ (input) [0] .value;

if (login.length> 0)

{

var params = "{login: '" + login + "'}" ;

ExecuteService (

params ,

"LoginService.asmx / CheckLogin" ,

callbackResult,

callbackError

);

}

}

* This source code was highlighted with Source Code Highlighter .




The CheckLogin JS function accepts through the textbox id parameters (in the form of "#id"), into which the login is entered, as well as two functions that determine what to do when receiving the result and when an error occurs. Notice the code



var params = "{login: '" + login + "'}";



- this is the formation of a JSON string to transfer the parameter to our web method, which, I recall, is defined as:



public bool CheckLogin (string login)



It should be noted that in the case when your web method does not accept any parameters, you need to write var params = "{}"; but not var params = "";. You should also know that at least in Firefox it is permissible to pass {login: “test”}, but in IE it will not work, so you need to use single quotes {login: 'test'}



We also define functions for passing callbackResult, callbackError:

function onCheckLogin (msg)

{

if (msg.d)

{

$ ( "#loginState" ) .text ( "OK" ) .css ( "color" , "green" );

}

else

{

$ ( "#loginState" ) .text ( "Invalid login" ) .css ( "color" , "red" );

}

}

function onError (XMLHttpRequest, textStatus, errorThrown)

{

$ ( "#loginMessage" ) .text ( "Error performing an AJAX request. Try reloading the page." );

} * This source code was highlighted with Source Code Highlighter .




Pay attention to msg.d. This is where the value that will return after the execution of the web method will lie. It is also necessary to clarify that #loginState is the id of the element, to display the result of checking the login, and #loginMessage is the id of the element, to display an error message.

Finally, we come to the final touch, we connect to the textbox a focus loss event handler:

$ ( "#txtLogin" ) .blur ( function () {CheckLogin ( "#txtLogin" , onCheckLogin, onError);})) * This is a code that was highlighted with Source Code Highlighter .




As you can see from the code, using the jQuery functions, the OnBlur event handler is registered for the control, which is declared as

< input id = "txtLogin" type = "text" /> * Source Code Highlighter .




Now, when the user enters the login text in the input field and moves to another element, for example to enter a password, a request will be automatically sent to the web server to determine the correctness of the login entry.



Conclusion



jQuery makes it very easy to access any .Net web services and web methods. In this note, the requirements for such requests were defined and a function was implemented that transparently calls .Net methods accepting only the url and parameters. An example of the use of this function for the automatic validation of usernames entered by the user was also considered.



PS: in addition, you can read the following article on this topic (only for .Net blog subscribers)

ajax.net vs jquery.ajax

habrahabr.ru/blog/net/44190.html

Source: https://habr.com/ru/post/27054/



All Articles