Search code examples
c#ajaxcorswebmethod

calling external web service from code behind vs client side


I am learning about web services so I set up a test environment based on this tutorial. I then created a web app project within the same solution and successfully called the service after setting up a web reference. I then attempted to call the service using ajax. I got the CORS error. I'm not well versed on 'CORS' so I decided to create a web method in the code behind that would then call the external service. It works with no errors. It got me wondering what "best practice" is for calling external service from the client. Should you try calling direct or should you call a web method that then calls the service?


Solution

  • In my opinion, calling external services / APIs from the back-end is frequently the best option. It has multiple benefits such as:

    1. Safety. Errors or exceptions that arise from the service can be easily handled.
    2. Control. Responses and data can be filtered and parsed prior to displaying it client side.
    3. Speed. If you want to do any calculations on the response, this will typically be faster to perform server side than client side.
    4. Testability. Writing these calls in the back-end will allow you to more easily unit test your request to an external service via common testing frameworks like XUnit