【问题标题】:How to return a JSON from WebAPI using http request?如何使用 http 请求从 WebAPI 返回 JSON?
【发布时间】:2021-08-31 07:12:21
【问题描述】:

我正在尝试实现一个新的 Web API。此 API 从 HTTP 请求返回 JSON。 到目前为止,我编写了非常基本的代码,但奇怪的是我在使用 XML 模板时遇到了一个错误——我不知道该怎么做: 这是调用:http://localhost:55643/api/ShipmentsStatus/getShipmentsStatusJSON

代码在这里:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace RunCom.WebAPI.Controllers
{
[Route("api/[controller]")]
public class ShipmentsStatusController : ApiController
{
    // /api/ShipmentsStatus/getShipmentsStatusJSON

    public ShipmentsStatusController()
    {
        int i = 0;
    }

    [HttpGet]
    [Route("getShipmentsStatusJSON")]
    
    public IEnumerable<String> Get()
    {
        test check = new test("1");
        yield return JsonConvert.SerializeObject(check);
    }

}

    internal class test
    {
        string key;
        public test(string k)
        {
            key = k;
        }
    }
}

我得到的错误在这里:

<Error>
<Message>No HTTP resource was found that matches the request URI 
'http://localhost:55643/api/ShipmentsStatus/getShipmentsJSON'.</Message>
<MessageDetail>No action was found on the controller 'ShipmentsStatus' that matches the request.</MessageDetail>
</Error>

我的代码有什么问题?

【问题讨论】:

标签: c# asp.net json xml asp.net-web-api


【解决方案1】:

尝试修复路线


    [Route("~/api/ShipmentsStatus/GetShipmentsStatusJSON")]
     public IEnumerable<string> Get()
    {
        return new List<string> {"1","2","3"};
    }

【讨论】:

  • 我得到运行时错误 var serializer = new XmlSerializer(type);
  • 请现在再试一次
  • 工作。我的解决方案不正确
【解决方案2】:

您应该使用http://localhost:55643/api/ShipmentsStatus/getShipmentsStatusJSON 或将[Route("getShipmentsStatusJSON")] 更改为适当的API 方法名称

【讨论】:

  • 还没有工作
猜你喜欢
  • 2020-06-24
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2017-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多