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

末鹿安然 提交于 2019-12-06 22:41:21

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/16932623/what-is-the-advantage-of-using-web-api-over-web-method-in-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!