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

2

8

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?

Sycosis answered 5/6, 2013 at 6:3 Comment(0)
R
15

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.

Rotl answered 5/6, 2013 at 6:8 Comment(0)
O
3

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.

Optimism answered 11/7, 2013 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.