【问题标题】:Web API Post call from c# client always return with 200 OK来自 c# 客户端的 Web API Post 调用总是返回 200 OK
【发布时间】:2014-12-23 17:27:01
【问题描述】:

我有一个像这样执行 POST 调用的 C# 客户端:

public void Add(ModelA newObj)
{
           HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create("http://www.x.com/api/ModelA");
           string json = JsonConvert.SerializeObject(newObj, Formatting.None,
           new  JsonSerializerSettings { 
            PreserveReferencesHandling = PreserveReferencesHandling.All
            });
            var messagebyte = Encoding.ASCII.GetBytes(json);
            httpRequest.Method = "POST";
            httpRequest.ContentType = "application/json";
            httpRequest.ContentLength = messagebyte.Length;
            // Send request
            using (var stream = httpRequest.GetRequestStream())
            {
                stream.Write(messagebyte, 0, messagebyte.Length);
                stream.Close();
            }
            // Get response
            using (var response = httpRequest.GetResponse() as HttpWebResponse)
            {
                response.Close();
            }
}

控制器看起来像这样:

[ResponseType(typeof(ModelA))]
public IHttpActionResult PostModelA(ModelA newModelA)
{
            return NotFound();
}

令人惊讶的是,客户端的响应是 200 OK。此外,“response.Method”的属性是“GET”而不是“POST”。我在这里错过了什么?

【问题讨论】:

  • 显然,我的 POST 调用被路由到 GET。我已将“return NotFound()”放在 GET 处理程序下,但出现“未找到”错误。这个问题变得非常奇怪

标签: rest c#-4.0 asp.net-web-api2


【解决方案1】:

好的,显然我的网络主机更改了一些配置,API 调用应该是http://x.com 而不是http://www.x.com

我是在尝试使用https://www.hurl.it/ 的服务执行 POST 调用时发现的,并且调用返回了类似的内容:

HEADERS

Content-Length: 163
Content-Type: text/html; charset=UTF-8
Date: Mon, 29 Dec 2014 04:40:55 GMT
Location: http://x.co/api/ModelA
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
X-Powered-By-Plesk: PleskWin
BODY view raw

<head>
  <title>Document Moved</title>
</head>
<body>
  <h1>Object Moved</h1>This document may be found 
  <a HREF="http://x.com/api/ModelA">here</a>
</body>

【讨论】:

    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 2022-10-04
    • 2019-03-02
    • 2012-08-14
    • 2019-07-01
    • 2015-04-26
    • 1970-01-01
    • 2015-01-04
    相关资源
    最近更新 更多