Web API GET vs POST - c#

I initially setup a Web API (not any expert with web api) and followed someone's tutorial online for passing in parameters to a simple get API call.
I had originally created a GET with query strings but as the tutorial showed how using POST allows me to pass JSON to an class object in POST API parameter, it seemed a good idea.
Later on one developer said this was bad practice? Is it? Should I always use GET instead of POST which in essence is what it should be anyway... a GET call, but I like the idea of passing parameters via an object and avoiding a long API call with query strings.
So:
$.ajax({
url: '\api\getlist\1?param2=yyyy&param3=kikkkk&param4=88' etc
})
or
var params = ....
$.ajax({
url: '\api\getlist\',
data: params
})
What should I do, change the code back to using GET? What about caching?

You should take a look at the http documentation in w3c.
GET is recommended for reading data and POST is used to send information (write operations) into the server.
From client side perspective, you could set in jquery ajax setup, to do not use cache with the follow code:
$.ajaxSetup({
cache: false
});
It will generate a random argument on the async request to make a different request everytime, add a parameter like this: ?_=31312312312.

Related

ASP.NET HTTP PUT and DELETE produce 404 status

I am trying to get familiar with ASP.NET, but I'm stuck at this basic thing.
So this is my HomeController.
I am using postman to simulate HTTP requests, but only GET method is working. PUT and DELETE both produce 404.
I have tried changing all the annotations to HttpGet, just to make sure that I'm targeting a correct method in my URL and it produces correct results. When I change the annotations back to HttpPut and HttpDelete, with the same links (but changed methods accordingly in postman) I get 404 again...
What am I doing wrong?
seems you are calling bad just need make the request without the method like this
http://localhost:5237/Home
don't use "/Put" same rule for "Delete" or "Post"
if your are using jQuery ajax
$.ajax({
url: 'http://localhost:5237/Home',
type: 'PUT'<---GET, POST, PUT, DELETE
....
})
I reproduced the scenario and tested through POSTMAN its working for me.
Please select the verb as in figure
Seems the url to be used as below where xxxx is port number:
PUT = (http://localhost:xxxx/home/put)
DELETE = (http://localhost:xxxx/home/delete)
#Nemanja, Please let me know if this works.

Securing API key used to make Web Api call

I am making a Jquery Ajax web api call . That Api call requires me to pass the Api key. I have enabled CORS. Here is how my call looks currently
$.ajax({
type: "POST",
url: http://localhost:83/test/example1,
data: { name: JSON.stringify(myObject), userId: UserId },
dataType: "json",
headers: {
'apikey': 'asdfee'
});
My question is how do I securely pass this key? I don't want to directly expose the value.
Any directions please?
In short, you cannot secure the key on the client side. Anything on the client side is exposed and can be viewed by anyone.
This being said, there are ways you can attempt this.
Try to make it as hard as possible for anyone trying to get your key. This means store in something like local storage and minify your JavaScript code. This isn't 100% but it will make life harder for anyone trying to get it.
Introduce another layer in between. I have done something like this myself, this extra layer is another API. This is where you store the key and this is where you communicate with the other API. So basically you never expose the API key to the client side. Your front end call this new API and the new API calls the protected one. As I said, one extra layer in between but it does help keep the key secure.

How to implement a callback URL to receive a json data in c#

For some days now i have been struggling on a project where i need to provide a URL to enable me to receive a JSON response(precisely this my first time of calling a web API)
This is the scenario:
- First the company has a web service that i need to consume and send a bill prompt to our client and so far it has been successful
- Second , they ask me to implement a callback and give them the URL where they will call me to send the status of the bill whether our client has confirm the bill prompt or not(this is where i am stacked)
When i get the JSON data i can easily use it to do what i want but my problem is how to implement the web page that the company will call to send the status.
Please a sample code will help me a lot.Thanks
What you are trying to achieve is called WebAPI. You expose HTTP endpoints using Controllers to the Internet and consumers of your API may utilize them to POST the status back.
You are describing creating an API. Basically, you create an endpoint url using a controller in C#. It's within this controller that you receive data from "the company" and process it, and do whatever you need to do after that. If you use the standard MVC framework build into C#, it's fairly straight-forward. Here is an example of a callback url we are using in a three-legged OAuth procedure. The last step involves a third party sending a request to our callback url and posting some data. We are using a model as a parameter. But you can use simple structures (int, string, etc) as well. As log as the names of your params match the names that the third party sends in their query string or POST, the MVC framework will handle the variable assignment automatically. The serialization/deserialization is built in to the framework.
Here is a small example of how we have implemented a callback url in one of our apps:
public class MyAuthenticatedController : Controller
{
public ActionResult Index([FromUri]MyAuthenticatedModel model)
{
logTheResponse(model);
if (model == null)
{
throw new HttpException(401, "Auth Failed");
}
}
}
The third party would hit the url:
http://app.mydomain.com/myauthenticated
Using the GET method.
If you don't want to build an ASP.NET Web API Project, you can do this easily with an Azure Function.
See: https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-generic-webhook-triggered-function

Making restful calls to asp.net web api

I am currently following this tutorial to create a simple REST service using Web Api. Note this is my first time doing something like this and I am just trying to learn more.
http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations
I have followed all the instructions and have it successfully running on my localhost. I understand that in this tutorial the URI for all my GET requests look something like:
localhostapi/products/id
And I understand that, and how to perform simple GET requests in the URI and see it actually occuring using my developer tools in my browser.
Now my question is... How do I make POST/DELETE/PUT requests and actually see what they are doing? The guide wasn't too clear, do I pass in parameters into the URI? Does the URI change when I want anything but a GET request? This text here seems to explain it but I do not understand:
The method takes a parameter of type Product. In Web API, parameters with complex types are deserialized from the request body. Therefore, we expect the client to send a serialized representation of a product object, in either XML or JSON format.
It's quite easy to make POST, PUT, DELETE requests. You just need to install Fiddler at http://www.telerik.com/download/fiddler
Next, install and run it. Go to the Composer tab on the right hand side. Next, put your local host URL, and the request method, and other data like the screenshot below
You can write unit tests, like
[TestMethod]
public void GetAllProducts_ShouldReturnAllProducts()
{
var testProducts = GetTestProducts();
var controller = new SimpleProductController(testProducts);
var result = controller.GetAllProducts() as List<Product>;
Assert.AreEqual(testProducts.Count, result.Count);
}
This link also This one may help.
more:
How to call ASP .NET MVC WebAPI 2 method properly
Sending C# object to webapi controller
You can set a breakpoint on your controller methods that handle the post/delete/put.
Same thing in your browser at the point where you call the post/delete/put (presumably in a jquery request)
You can also unit test your controller methods:
http://www.asp.net/mvc/tutorials/older-versions/unit-testing/creating-unit-tests-for-asp-net-mvc-applications-cs

How to cache .NET Web API requests (& use w/ AngularJS $http)

I have a Web API written in ASP.NET that I'm consuming via AngularJS $http.
I have enabled caching in my AngularJS factory as follows but every request still returns a response of 200, never 200 (from cache) or 304 (and by every request I mean making the same web api request numerous times on the same page, revisiting a page I've already visited that contains a Web API request, refreshing said page etc).
angular.module('mapModule')
.factory('GoogleMapService', ['$http', function ($http) {
var googleMapService = {
getTags: function () {
// $http returns a promise, which has a 'then' function, which also returns a promise
return $http({ cache: true, dataType: 'json', url: '/api/map/GetTags', method: 'GET', data: '' })
.then(function (response) {
return response.data;
});
};
return googleMapService;
}]);
Am I missing something from the AngularJS side of things? Or is this a Web API problem. Or both?
Turns out it was a Web API thing. I'd overlooked the fact that the response header clearly stated that caching was disabled.
Response as viewed in the Network tab of Google Chrome:
Upon further investigation (and as seen in the image above), caching is disabled in Web API controllers. Even the [OutputCache] attribute, which is used in regular MVC controllers, isn't supported.
Luckily I found this blog:
http://www.strathweb.com/2012/05/output-caching-in-asp-net-web-api/
which lead me to these two solutions:
ASP.NET Web API CacheOutput
CacheCow
I decided to go with CacheOutput as it lets me use attributes like:
[CacheOutputUntilToday] which supports server & client side caching.
Or if I wanted to just use client-side caching I can use something like:
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 0)]
Which seemed a little easier at first glance that CacheCow's approach. And easier to refactor out later if need be.
Now additional requests give me a 200 (from cache):
With a refresh giving me a 304 Not Modified:
Problem solved! Hope this helps someone else.

Categories

Resources