Web API Interview Questions
Q1. FromBody vs From
Uri
1. 1. Default convention used by Web API for binding
parameters.
2. If the parameter is a
simple type like int, bool, double, etc., Web API tries to get the value from
the URI (Either from route data or Query String)
3. If the parameter is a
complex type like Customer, Employee etc., Web API tries to get the value from
the request body
public HttpResponseMessage Put([FromBody]int id,
[FromUri]Employee employee)
{
1.
// We have decorated id parameter with [FromBody] attribute, this
forces Web API to get it from the request body
2.
We have decorated
employee parameter with [FromUri] attribute, this forces Web API to get employee data from the
URI (i.e Route data or Query String)
4.
Bearer token Example:
Please note :
1. sessionStorage data is lost when the browser window is closed.
2. To store an item in the browser session storage use setItem() method
Example : sessionStorage.setItem("accessToken", response.access_token)
1. sessionStorage data is lost when the browser window is closed.
2. To store an item in the browser session storage use setItem() method
Example : sessionStorage.setItem("accessToken", response.access_token)
3. To
retrieve an item from the browser session storage use getItem() method
Example : sessionStorage.getItem("accessToken")
4. To remove an item from the browser session storage use removeItem() method
Example : sessionStorage.removeItem('accessToken')
Example : sessionStorage.getItem("accessToken")
4. To remove an item from the browser session storage use removeItem() method
Example : sessionStorage.removeItem('accessToken')
Caling
bearer token :
<script type="text/javascript">
$(document).ready(function () {
$('#linkClose').click(function () {
$('#divError').hide('fade');
});
$('#btnLogin').click(function () {
$.ajax({
// Post username, password & the grant type
to /token
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
username: $('#txtUsername').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
// When the request completes successfully, save
the
// access token in the browser session storage
and
// redirect the user to Data.html page. We do not
have
// this page yet. So please add it to the
// EmployeeService project before running it
success: function (response) {
sessionStorage.setItem("accessToken", response.access_token);
window.location.href = "Data.html";
},
//
Display errors if any in the Bootstrap alert <div>
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
});
</script>
</body>
</html>
*Generate token :
Request bodfy:
username=DotNetByPriyanshu@gmail.com&password=Pass@1366&grant_type=password
·
Authroize suer calling :
Request Header :
User-Agent: Fiddler
Host: localhost:51658
Authorization: Bearer
U_C4EnP3H5_nDRtY7ze7PTqFNBmnprUCLruU4uKTABu80q5lZHqPGaI8hiN8tqvoRFVpQmwIv_--_YyOYCc89jz5los-Ay2FObx6FIChtkd4U-Z_W2ULcU05sJ7IKaDlCfur1in1XKB5AopJg7RZ_HSMfR_PRMyKQn0oskktA3jsTudCRQ8c2CVZVuUTp_YJJ4yYXEPIuT6wODBNqzDJ3gs9cNSTAUfuyueEDTzU2q5whUkYm18eYt3WQOYfRT_qBCxKYamrkfYNMPxItzkzGUlQzu5r8lMforOa5GzZuhEFZgIbNsEjdXlPh1YF8BWz7NfzIXKz7G1d7p79O3ASrPXxvn6fmJTIck-iusvsSmRgUxnwX1gstFhnRlza_ZHyoZKvYiNCpC3uX65679dZAj06KNv1846Rn3vmtq4s8msY778e8hATSspkfVcc7F6PBYj_H6ySHhr9G5KQHPi7eMlilKOlH1WkvGnpcWzrDKtnMyZcyKXcB6NQgYCwz33E
** Content negotiation
Accept header the
client can specify the format for the response. For example
Accept:
application/xml returns XML
Accept:
application/json returns JSON
If you don't specify
the Accept header, by default the Web API returns JSON data.
Host: localhost:51857
Accept:
application/json
Content-type:
application/json
Content-Length: 75
** POST VS PUT
if you make the same request twice using PUT, with the same
parameters both times, the second request will have no effect. This is why PUT is generally used for the Update scenario;
calling Update more than once with the same parameters doesn't do anything more
than the first call did.
By contrast, POST is not idempotent; making the
same call using POST with same parameters each time will cause two different
things to happen, hence why POST is commonly used for the Create scenario
(submitting two identical items to a Create method should create two entries in
the data store).
**Put
and Post both are safe. Let say u send 2 request by using same parameters they
the second one dont have any relevance in case of Put.But in case of post its
vice versa.Making two request with same parameter it will create two different
result :)
**GET AND POST
The Hypertext Transfer Protocol (HTTP) is a
communication protocol that is designed to enable request-response between
clients and servers. Here, a web browser is the client and an application on a
computer that hosts a web site is the server:
Get request is idempotent . It means second request will be ignored until
response of first request is delivered
Post request is non-idempotent.
HTTPGET post
Parameters remain in browser history because they are part of
the URL
|
Parameters are not saved in browser history.
|
|
Bookmarked
|
Can be bookmarked.
|
Can not be bookmarked.
|
BACK button/re-submit
behaviour
|
GET requests are re-executed but may not be re-submitted to
server if the HTML is stored in the browser cache.
|
|
Encoding type (enctype
attribute)
|
application/x-www-form-urlencoded
|
multipart/form-data or application/x-www-form-urlencoded Use
multipart encoding for binary data.
|
Parameters
|
can send but the parameter data is limited to what we can stuff
into the request line (URL). Safest to use less than 2K of parameters, some
servers handle up to 64K
|
Can send parameters, including uploading files, to the server.
|
Hacked
|
Easier to hack for script kiddies
|
More difficult to hack
|
Restrictions on form
data type
|
Yes, only ASCII characters allowed.
|
No restrictions. Binary data is also allowed.
|
Security
|
GET is less secure compared to POST because data sent is part of
the URL. So it's saved in browser history and server logs in plaintext.
|
POST is a little safer than GET because the parameters are not
stored in browser history or in web server logs.
|
Restrictions on form
data length
|
Yes, since form data is in the URL and URL length is restricted.
A safe URL length limit is often 2048 characters but varies by browser and
web server.
|
No restrictions
|
Usability
|
GET method should not be used when sending passwords or other
sensitive information.
|
POST method used when sending passwords or other sensitive information.
|
Visibility
|
GET method is visible to everyone (it will be displayed in the
browser's address bar) and has limits on the amount of information to send.
|
POST method variables are not displayed in the URL.
|
Cached
|
Can be cached
|
Not cached
|
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete