如何在2个MVC站点之间传递HttpStatusCode?

时间:2017-09-25 02:27:44

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

我有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响应...]处的断点)总是" StatusCode:200,ReasonPhrase:' OK',版本:1.1"无论HttpStatusCode我设置为(B)发回。

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

1 个答案:

答案 0 :(得分:0)

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

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