How would I call an ASP.NET Web API directly from code-behind? Or should I be calling my javascript function that calls the getJSON method from code-behind?
I usually have something like:
function createFile() {
$.getJSON("api/file/createfile",
function (data) {
$("#Result").append('Success!');
});
}
Any pointers appreciated. TIA.
*I'm using WebForms.
If you must call the web service itself, you can try using
HttpClient
as described by Henrik Neilsen.Updated HTTPClient Samples
A basic example:
Recommended in many software architecture books is that you shouldn't put any business logic in your (API)controller code. Assuming you implement it the right way, for instance that your Controller code currently accesses the business logic through a Service class or facade, my suggestion is that you reuse the same Service class/facade for that purpose, instead of going through the 'front door' (so by doing the JSON call from code behind)
For basic and naieve example:
AppService class encapsulates your business logic (and does live on another layer) and makes it easier for you to access your logic:
You should refactor the logic into a separate backend class and call it directly from youir code-behind and from the Web API action.