【发布时间】: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; }
}
【问题讨论】:
-
这可能有用。 HttpClient 比 HttpWebRequest 更容易使用。 stackoverflow.com/questions/4015324/http-request-with-post我的钱会花在一些表单格式问题上。
-
请作为答案发布。
标签: json asp.net-mvc asp.net-web-api