简体   繁体   English

REST API 未返回预期结果

[英]REST API not returning expected results

I'm trying to follow the article Build RESTful API's with ASP.NET Web API to learn how to create a RESTful API.我正在尝试按照文章Build RESTful API's with ASP.NET Web API来学习如何创建 RESTful API。

I created the first project and controller, Contact .我创建了第一个项目和控制器Contact

public class ContactController : Controller
{
    // GET: Contact
    public string[] Index()
    {
        return new string[]
        {
            "Hello",
            "World"
        };
    }
}

But when I load the URL in a browser, instead of getting the response described in the article ( ["Hello","World"] ).但是当我在浏览器中加载 URL 时,而不是获得文章中描述的响应( ["Hello","World"] )。 The response I get is System.String[] .我得到的响应是System.String[]

I don't understand what I'm missing.我不明白我错过了什么。

BTW, the article is from 2013. Does anyone know of a good article that is perhaps a little newer?顺便说一句,这篇文章是2013年的。有谁知道一篇可能更新一点的好文章?

What you have now is simple ASP.NET MVC controller.您现在拥有的是简单的 ASP.NET MVC 控制器。 For Web API controller you should inherit your controller from ApiController instead of Controller :对于 Web API 控制器,您应该从ApiController而不是Controller继承您的Controller

public class ContactController : ApiController

Also action names should start with HTTP verb.动作名称也应该以 HTTP 动词开头。 If you'll send GET request to /api/contact endpoint you'll get error如果您将 GET 请求发送到/api/contact端点,您将收到错误

The requested resource does not support http method 'GET'.请求的资源不支持 http 方法“GET”。

By default action name is not used in route for Web API controllers.默认情况下,Web API 控制器的路由中不使用操作名称。 If you'll check default route configuration, it will be api/{controller}/id .如果您要检查默认路由配置,它将是api/{controller}/id Correct action is selected via HTTP method of request.通过请求的 HTTP 方法选择正确的操作。 In your case it should be GetXXX or simply Get在您的情况下,它应该是GetXXX或只是Get

You cannot Return regular primitives from the Web Apis.您不能从 Web API 返回常规原语。 At least if not if you are using a regular MVC Web API from .net.至少,如果您使用的是来自 .net 的常规 MVC Web API,则不会。 So, if this is the case you could do something like所以,如果是这种情况,你可以做类似的事情

public class ContactController : Controller
{
    // GET: Contact
    public JsonResult Index()
    {   
        return Json(new { value1: "Hello", value2: "world" }, JsonRequestBehavior.AllowGet);

    }
}

Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM