【问题标题】:Posting JSON to WebAPI2 function将 JSON 发布到 WebAPI2 函数
【发布时间】:2015-09-09 07:26:06
【问题描述】:

我在 MVC 应用程序控制器中有以下代码,用于通过 WebAPI2 调用使用 EF6 发送一些要存储在存档表中的数据。

即使我设置为 POST 并且 api 调用被定义为仅接受 POST,我仍然收到“无法发送具有此动词类型的内容正文”。

我到底做错了什么,我该如何解决?

ArchiveUploadModel.ArchiveUpload obj = new ArchiveUploadModel.ArchiveUpload();

obj.LT = LT;
obj.PID = PID.ToString();
obj.Title = "Ex Review";
obj.HTML = message.Body; // the HTML is a rendered HTML email message 

if (!string.IsNullOrEmpty(obj.HTML))
{
    HttpWebRequest req = HttpWebRequest.Create("http://example.com/MyApp/api/UploadToArchive") as HttpWebRequest;
    request.ContentType = "application/json";
    request.Method = "POST";
    string json = JsonConvert.SerializeObject(obj);

    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
    }
}
using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
{
    using (StreamReader reader = new StreamReader(webresponse.GetResponseStream()))
    {
        string response = reader.ReadToEnd();
    }

}

这是我的 WebAPI 调用的代码:

[HttpPost]
[Route("api/UploadToArchive")]
[EnableCors("http://example.com",                      // Origin
            "Accept, Origin, Content-Type, Options",   // Request headers
            "POST",                                    // HTTP methods
            PreflightMaxAge = 600                      // Preflight cache duration
)]
public IHttpActionResult UploadToArchive(ArchiveUpload upload)
{
    string HTML = upload.HTML;
    string Title = upload.Title;
    string LT = upload.LT;
    string lt = getLT(upload.PID); // essentially secure checking to see if it matches passed LT.
    if (lt == LT)
    {
        // Upload the file to the archive using the ArchiveRepository's UpdateArchive() function:
        _ArchiveRepository.UpdateArchive(HTML, System.Web.HttpUtility.HtmlDecode(Title), "", upload.PID);
        return Ok(PID);
    }
    else
    {
        return BadRequest("Invalid LT");
    }
}

ArchiveUpload 两个应用程序中的模型定义:

public class ArchiveUpload
{
    public string LT { get; set; }
    public string PID { get; set; }
    public string Title { get; set; }
    public string HTML { get; set; }
}

【问题讨论】:

标签: json asp.net-mvc asp.net-web-api


【解决方案1】:

最好尝试使用 Microsoft Http 客户端库。您可以从 nugethere 安装它,您可以找到使用不同 HTTP 动词调用 Web API 的示例

【讨论】:

  • 这样做但有另一个不相关的问题。
猜你喜欢
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-05
  • 1970-01-01
  • 2014-02-08
  • 2021-12-16
相关资源
最近更新 更多