简体   繁体   English

在ASP.NET MVC Web Api中返回Json

[英]Returning Json in ASP.NET MVC Web Api

I am trying to learn how to create an API with ASP.NET MVC (I'm using vNext). 我正在尝试学习如何使用ASP.NET MVC创建API(我正在使用vNext)。 To do this, I'm just trying to return the current date. 为此,我只是想返回当前日期。 At this time, I have the following: 目前,我有以下内容:

using System;
using Microsoft.AspNet.Mvc;

[Route("api/test")]
public class TestController : Controller
{
  [HttpGet("date")]
  public string Date()
  {
    return Json(new { result = 1, currentDate = DateTime.UtcNow });   
  }
}

I execute this from fiddler via the composer tab. 我通过作曲家标签从提琴手执行此操作。 When I do that, http://localhost:5001/api/test . 当我这样做时, http://localhost:5001/api/test I press Execute. 我按执行。 The result is a status code of 200. However, there is no JSON. 结果是状态码200。但是,没有JSON。 Instead, I get the "Welcome Your ASP.NET vNext application has successfully started" page. 而是显示“欢迎您的ASP.NET vNext应用程序已成功启动”页面。

What am I doing wrong? 我究竟做错了什么?

Your ActionResult seems to be invalid: 您的ActionResult似乎无效:

Try with " JsonResult " and Allowed Json behavior. 尝试使用“ JsonResult ”和允许的Json行为。

public class TestController : Controller
{
    [Route("api/test")]
    public JsonResult Date()
    {
        return Json(new { result = 1, currentDate = DateTime.UtcNow }, JsonRequestBehavior.AllowGet);
    }
}

You Also need to enable Attribute routing in RouteConfig class: 您还需要在RouteConfig类中启用属性路由:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

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

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