使用HttpClient发布并读取HttpResponseMessage状态

时间:2018-10-21 14:34:39

标签: c# asp.net-core asp.net-core-mvc

我正在使用$cat = array('Annual Fee-Disability Scholarship','Annual Fee-First rank Scholarship','Monthly Fee-First rank Scholarship'); $amount = array('1000-20','1000-10','560-5'); $outputed_fee_cat = []; foreach (array_combine($cat, $amount) as $cat => $amount){ $cat_ry = explode('-', $cat); $amount_ry = explode('-', $amount); $fee = $amount_ry[0]; $sch_cat = $cat_ry[1]; $sch = $amount_ry[1]; $fee_cat = $cat_ry[0]; if (!in_array($fee_cat, $outputed_fee_cat)) { $outputed_fee_cat[] = $fee_cat; echo " <tr> <td class='bold'>$fee_cat</td> <td>$fee</td> </tr>"; } echo " <tr> <td>$sch_cat</td> <td>$sch</td> </tr>"; } 发布到API,然后返回HttpClient。 我正在从回复中读取状态代码,但始终为HttpResponseMessage

发布:

200

我正在从API回复var json = JsonConvert.SerializeObject(loginDto); var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); var client = new HttpClient(); var response = await client.PostAsync("http://localhost:57770/api/Account/Login", stringContent);

HttpResponseMessage

但是当我读到return new HttpResponseMessage(HttpStatusCode.Unauthorized); 时,它总是response

我该如何实现?

1 个答案:

答案 0 :(得分:3)

Asp.Net Core不再将HttpResponseMessage识别为管道的一部分。这意味着它将像其他返回的模型一样对待并序列化为内容。因此状态为200 OK。

API控制器操作应返回IActionResult派生的结果。

[HttpPost]
public IActionResult SomeAction(...) {

    //...

    return StatusCode((int)HttpStatusCode.Unauthorized); //401

    //...
}

或者只是使用

return Unauthorized(); 
StatusCodeResult衍生而来的

,用快捷键来代替上面显示的代码。

参考ControllerBase.Unauthorized