代码之家  ›  专栏  ›  技术社区  ›  MB34

将JSON发布到WebAPI2函数

  •  2
  • MB34  · 技术社区  · 11 年前

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

    即使我设置为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; }
    }
    
    1 回复  |  直到 11 年前
        1
  •  2
  •   Hernan Guzman    11 年前

    最好尝试使用Microsoft Http客户端库。您可以从 nuget 和 here 您可以找到使用不同HTTP动词调用Web API的示例