What are the major differences between Web API and

2019-03-19 15:20发布

The title really sums up my question. I have used both technologies but I am uncertain as to what one offers that is substantially different than the other. In essence:

What criteria and/or guidance should one consider when selecting ASP MVC or Web API when designing a restful web application?

1条回答
走好不送
2楼-- · 2019-03-19 16:08

Purpose

ASP.NET MVC is focused on making output of HTML easy. ASP.NET Web API is focused on making output of raw data easy.

In the WebForms world, ASP.NET MVC would be equivalent to .aspx pages and ASP.NET Web API would be .asmx.

Although nothing is impossible

While it's possible to make Web API output HTML and MVC output raw data, you will need additional work. For example, making additional classes to handle text/html during content negotiation in Web API, or adding logic to handle OData queries in MVC.

Assumptions

The default assumption for both MVC and Web API are different too. MVC by default assumes user submitted data can come from multiple sources, be it in the query string or in the form.

Web API by default assumes that primitive type comes from query string and non-primitive types comes from the form. It also assumes that you would only want to read the form body once, without caching, to have lower memory usage and better performance.

Going against the defaults requires additional work, that to me, does not make sense at all.

EDIT:

Also, GET AJAX request is blocked by MVC's JsonResult by default to prevent CSRF, while Web API allows GET AJAX request by default.

Update for MVC 6

MVC 6 unifies MVC and Web API and allows you to return ViewResult like in MVC or object like in Web API, and the framework will take care of content negotiation, creating the HTML, JSON or XML for you. Lower memory usage also arrives in MVC, by using its custom pipeline instead of what is provided by System.Web.

So going forward, there's no distinction between the MVC and Web API.

查看更多
登录 后发表回答