Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using web API over web method in ASP.NET

I am familiar with web method. Now I got a suggestion to use web API instead of web method. I had done a demo of ASP.NET web API it's more closer to a MVC architecture am using the classical asp.net web development. I don't like to mess up the controller (MVC concept) with classical development.

My web Method :

[WebMethod]
public static string GetName(int id)
{
    return "testName";
}

My Web API controller:

public class MyController : ApiController
{
[HttpGet]
public string GetName(int id)
{
    return "testName";
}
}

am really confused on this issue any one have a better idea on the same.

What is your suggestion on the same which is the better option?

How can i compare, if both having same piece of code?

like image 561
Arun Chandran C Avatar asked Jun 05 '13 06:06

Arun Chandran C


2 Answers

The classic ASP.NET WebServices (what you call WebMethod) are a deprecated technology. There is no longer any active development. The ASP.NET Web API is a complete rewrite of the web stack from Microsoft in which you have far greater control for creating RESTful web services. This doesn't mean that you should choose between one or the other. There's also ServiceStack. If you are starting a new project you should stay away from classic webservices. If they are still present in the .NET framework it is for compatibility reasons with legacy code.

like image 119
Darin Dimitrov Avatar answered Nov 15 '22 20:11

Darin Dimitrov


Complementing Darin's answer, if you want to test your method from ApiController, you can inject the object's dependencies using an DI container (http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver). The dependency injection is done automatically.

However, with webmethods, you can't use DI in that way because webmethods must be static. If you insist in using DI, you need to instantiate and call the container directly in each of the webmethods to get the dependencies to work on.

like image 44
Fabio Avatar answered Nov 15 '22 19:11

Fabio