首页 > 解决方案 > 我的服务返回 200 状态码,但我的 MVC 控制器 IsSuccessStatusCode 返回 FALSE

问题描述

我有一个用 .NET 开发的 Web 服务,在一个 Web API 中,它有一个执行新用户注册的控制器。记录完成后,它返回HttpActionResult200 HttpStatusCode(OK),但我在 MVC 中的项目控制器将其解释为 500(内部服务器错误)。我已经这样做了几个小时,我找不到原因。这不是在控制器后面运行的任务中try / catch的错误,因为会抛出错误,这不会发生。这是给我这些问题的服务控制器的唯一方法。知道为什么会发生吗?

这是我的 Web API 控制器的方法(发件人):

public IHttpActionResult RegisterAttendee(ParticipantDTO participantDto)
{
    if (!ModelState.IsValid)
        return BadRequest();
    int result = _context.RegisterParticipant(participantDto);
    return Content(HttpStatusCode.OK, result);
}

这是我的 MVC 控制器的方法(接收器):

    [HttpPost]
    [AllowAnonymous]
    [ValidateJsonAntiForgeryToken]
    public async Task<ActionResult> RegisterParticipant(RegisterIndexBaseVm attendee)
    {
        if (attendee == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        if (ModelState.IsValid)
        {
            attendee.EventId = Int32.Parse(Session["id"].ToString());
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(BaseUrl);
                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage Res = await client.PostAsync("Register/RegisterAttendee", new StringContent(JsonConvert.SerializeObject(Mapper.ToParticipant(attendee)), Encoding.UTF8, "application/json"));
                if (Res.IsSuccessStatusCode)
                {
                    var EmpResponse = Res.Content.ReadAsStringAsync().Result;
                    var result = JsonConvert.DeserializeObject<int>(EmpResponse);
                    if (result == 0)
                        return Json(new { success = true }, JsonRequestBehavior.AllowGet);
                    else
                        return Json(new { success = false }, JsonRequestBehavior.AllowGet);
                }
            }
        }
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }

感谢您的支持

标签: c#asp.net-mvcweb-servicesasp.net-web-api

解决方案


推荐阅读