【问题标题】:GET request works, how to make POST work too?GET 请求有效,如何使 POST 也有效?
【发布时间】:2012-10-17 02:25:10
【问题描述】:

我有 MVC-4 Web-API 服务器,我需要“手动”(通过 TCP)创建 HTTP 客户端来与它通信。

public class UpdateUnitDetailsController : ApiController
{
    // GET api/updateunitdetails
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/updateunitdetails/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/updateunitdetails
    public void Post([FromBody]string value)
    {
    }

    // POST api/updateunitdetails
    public void Post()
    {
    }

    // PUT api/updateunitdetails/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/updateunitdetails/5
    public void Delete(int id)
    {
    }
}

我做了一个简单的客户端并在服务器控制器的方法中设置断点。在客户端,我发送这个:

GET /api/updateunitdetails HTTP/1.1
Host: localhost:58743

Content-Type: */*
Content-Length: 10

home=sweet

它可以工作(调试器在Get 方法中停止)。但是如果我将GET 更改为POST,它不会。此外,每当我发出 POST 请求时,我都会在 Visual Studio 控制台中看到以下消息:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.Http.dll

我错过了什么?

【问题讨论】:

    标签: http c#-4.0 post asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    改用这个:

    POST /api/updateunitdetails HTTP/1.1
    Host: localhost:58743
    
    Content-Type: application/x-www-form-urlencoded
    
    
    =sweet
    

    【讨论】:

    • 我不明白。这是GET,我正在尝试使用POST,而home=sweet 中的home 在哪里?你只留下了=sweet..?
    • 对不起,我的意思是 POST - 是的,由于 Web API 从正文绑定,整个正文 需要只是值,因此正文应该是 =sweet
    • 什么是 Content-Type: */* 应该是什么意思?我以前从未见过,你确定它有效吗?
    猜你喜欢
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2023-03-22
    • 2020-09-27
    • 2017-03-19
    • 2018-10-22
    相关资源
    最近更新 更多