【问题标题】:How to pass HttpStatusCode between 2 MVC sites?如何在 2 个 MVC 站点之间传递 HttpStatusCode?
【发布时间】:2017-09-25 02:27:44
【问题描述】:

我有 2 个MVC 站点。一个 (A) 正在向另一个 (B) 发帖。

MVC站点A:

using (var handler = new WebRequestHandler())
{
    handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

    using (var client = new HttpClient(handler))
    {
        using (var formData = new MultipartFormDataContent())
        {
            StreamContent fileStreamContent = new StreamContent();
            formData.Add(fileStreamContent, "file", HttpUtility.UrlEncode(Path.GetFileName("some test path")));

            var fileReceiveURL = "URL(B)\SomeController\PostFile";
            HttpResponseMessage response = client.PostAsync(fileReceiveURL, formData).Result;
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Not able to send file to (B). Didn't get a successful response from server.");
            }
        }
    }
}

MVC 站点 B(SomeController):

[HttpPost]
public HttpResponseMessage PostFile(HttpPostedFileBase file)
{
    \\ for testing purpose, just return a bad request response code
    return new HttpResponseMessage(HttpStatusCode.BadRequest);
}

但是在 (A)。响应([HttpResponseMessage response...] 处的断点)始终为“StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1”,无论我将什么 HttpStatusCode 设置为 (B) 发回。

如何在 2 个MVC 站点之间发送HttpStatusCode

【问题讨论】:

  • 您使用的是什么版本的 asp.net-mvc?如果您使用的是 asp.net-core 之前的版本,则站点 B 代码应该可以工作。如果使用 asp.net-core,那么所描述的行为将是准确的,因为该版本将从操作返回的 HttpResponseMessage 视为模型,并且在调用时默认为 200。提供minimal reproducible example,可用于重现和确认问题。
  • 两个网站都是 MVC 5。
  • 如果返回 200,那么响应的内容是什么。内容可以提供线索。
  • 您使用的是PostAsync,所以在调试时我不是百分百确定,但看到响应正常是正常的。因为默认情况下,在得到最终响应之前它被设置为 ok。
  • 请先尝试从 Fiddler、Postman 或 Advanced Rest Client 而非 MVC 站点进行检查。

标签: c# asp.net-mvc asp.net-mvc-5 http-response-codes


【解决方案1】:

而不是检查响应对象...

HttpResponseMessage response = client.PostAsync(fileReceiveURL, formData).Result;

响应总是返回 200 OK。

需要检查

HttpResponseMessage response = await client.PostAsync(fileReceiveURL, formData);
string responseString = await response.Content.ReadAsStringAsync();

response.Content 包含来自站点 B 的正确 HttpStatusCode

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 2011-08-19
    • 2021-10-04
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    相关资源
    最近更新 更多