【问题标题】:Return the List items from C# MVC Controller从 C# MVC 控制器返回列表项
【发布时间】:2020-11-17 19:54:51
【问题描述】:

所以我有这段代码,它应该返回项目列表,但我无法让它工作。我知道HttpResponseMessageList<string> 之间不匹配,但我无法将其转换为返回。

我知道这是因为HttpResponseMessage 类型和列表不匹配但我不知道如何转换它

namespace NovaWebApi.Controllers
{
    public class TermsController : WebApiBase
    {
        [HttpGet]
        public HttpResponseMessage GetTermsUrl()
        {
            List<string> terms = new List<string>();
            terms.Add("https://www.nbg.gov.ge/index.php?m=2");
            terms.Add("https://www.fms.gov.ge/");

            return terms;
        }
    }

}

【问题讨论】:

  • 图片中的信息告诉你出了什么问题。
  • 返回类型应该是 HttpResponseMessage 类型。 stackoverflow.com/questions/12240713/…
  • 如果这些答案都没有提供您可以接受的解决方案作为您的答案,请编辑您的问题以说明为什么他们不满足您的要求并提供更多详细信息。

标签: c# asp.net-mvc list


【解决方案1】:

您试图将List&lt;string&gt; 作为HttpResponseMessage 返回,这是不可能的。试试这个:

public class TermsController : Controller // this part to return Ok() without error.

然后:

return Ok(terms);

【讨论】:

  • 我试过了,但是“名称 Ok 在当前上下文中不存在”
  • 任何智能感知建议?
  • 只是为了生成一个新的Ok方法
  • 这并没有帮助抱歉。它搞砸了 [httpget],我将其更改为公共类 TermsController : WebApiBase,我们在不同的控制器中使用,但我仍然收到错误
  • 不是WebApiBase,应该使用Controller来继承。
【解决方案2】:

您的 HttpGet 方法返回 HttpResponseMessage。试试这个:

[HttpGet]

    public List<string> GetTermsUrl()
    {
        List<string> terms = new List<string>();
        terms.Add("https://www.nbg.gov.ge/index.php?m=2");
        terms.Add("https://www.fms.gov.ge/");

        return terms;
    }

【讨论】:

  • 是的,我做到了,效果很好,抱歉回复晚了。我还没有尝试过其他适合我的方法。
【解决方案3】:

由于您表示希望返回 HttpResponseMessage 类型,因此您必须创建一个包含您的列表的类型。

Web API 将使用模型的格式化程序在响应正文中创建一个序列化版本,在本例中是您的列表;将序列化模型写入响应正文。

[HttpGet]
public HttpResponseMessage GetTermsUrl()
{
     // Get a list of products from a database.
     List<string> terms = new List<string>();
     terms.Add("https://www.nbg.gov.ge/index.php?m=2");
     terms.Add("https://www.fms.gov.ge/");
     // Write the list to the response body.
     HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, terms);
     return response;
)

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 2014-10-13
    • 1970-01-01
    • 2017-08-12
    相关资源
    最近更新 更多