【问题标题】:Passing JSON Object to GET Method - ASP.Net ApiController将 JSON 对象传递给 GET 方法 - ASP.Net ApiController
【发布时间】:2020-11-25 03:53:54
【问题描述】:

我希望将 URI 字符串传递给我的 APIController 继承类中的 GET 方法。我已经尝试将它作为原始文本放入内容中,并且作为字符串参数没有运气。我已经制作了一个模型作为参数传递:

namespace ServerDock.Models.Web
{
    using System.Runtime.Serialization;

    [DataContract]
    public partial class UriWeb
    {
        [DataMember]
        public string Uri_String { get; set; }

        public UriWeb() { }

    }
}

现在我的Controller的功能如下:

[Route("file", Name = "Download")]
[HttpGet]
public async Task<IHttpActionResult> DownloadFile([FromBody] UriWeb uri)

使用 Postman 调用,其 JSON 正文如下:

{
    "Uri_String":"https://mysite.windows.net/files/ec0a30c8-265d-4c94-b176-387004f5f566-.jpg"
}

我在控制器函数中的断点从未被命中,我得到错误:请求正文不完整。

知道我做错了什么吗?

【问题讨论】:

    标签: asp.net rest asp.net-web-api httprequest


    【解决方案1】:

    [HttpGet] 更改为[HttpPost]。 GET 不能有[FromBody] 参数:

    [Route("file")]
    [HttpPost]
    public async Task<IHttpActionResult> DownloadFile([FromBody] UriWeb uri){...}
    

    如果必须使用 GET,则需要将其作为查询字符串传递。所以你可以把它改成:

    [Route("file")]
    [HttpGet]
    public async Task<IHttpActionResult> DownloadFile([FromQuery] Uri uri){...}
    

    然后这样调用它(查询字符串已经编码):

    http://example.com/api/file?uri=http%3A%2F%2Fexample.com%2Ffile.zip
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多