为什么在成功更新后,此HttpClient PutAsync会返回内部服务器错误

时间:2017-12-03 00:00:49

标签: c# .net asp.net-web-api2 httpclient internal-server-error

我有一个HttpPut API方法,可以编辑传递的对象并成功保存到数据库中。这工作正常,但是从我的MVC应用程序,我用来调用我的API Put方法的httpClient.PutAsync返回内部服务器错误,即使API Put方法没有。

我不确定出了什么问题,API方法工作正常,但不知何故,MVC HttpClient仍然会收到内部服务器错误。

API PUT方法

    [HttpPut]
    public IActionResult Put([FromBody] School school)
    {
        try
        {
            var schoolExists = _schoolRepository.SchoolExists(school.Id);

            if (!schoolExists) return NotFound();

            if (!ModelState.IsValid) return BadRequest();

            var schoolData = Mapper.Map<School, Data.School>(school);

            var updatedClass = _schoolRepository.UpdateSchool(schoolData);

            if (!updatedClass) return Json(GetHttpResponseMessage(HttpStatusCode.InternalServerError));

            var route = CreatedAtRoute("GetSchool", school);

            return route;
        }
        catch (Exception e)
        {
            return LogException(e);
        }
    }

上面的方法工作正常,我的更改保存到数据库中,并从API方法返回CreatedAtRouteResult对象。

MVC HTTPCLIENT

    public async Task<T> PutObject(string path, T content, string accessToken)
    {
        using (var httpClient = new HttpClient())
        {
            try
            {
                SetBaseUri(httpClient, accessToken);

                var serialisezContent = CreateHttpContent(content);

                var httpResponse = await httpClient.PutAsync(path, serialisezContent);

                if (httpResponse.StatusCode == HttpStatusCode.InternalServerError) throw new Exception("Problem accessing the api");

                return JsonConvert.DeserializeObject<T>(GetResult(httpResponse));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }

上面的方法是问题所在,此行var httpResponse = await httpClient.PutAsync(path, serialisezContent);仍然返回内部服务器错误。我的POST有相同的实现,并且工作得很好。

SETBASEURI()

    private void SetBaseUri(HttpClient httpClient, string accessToken)
    {
        httpClient.BaseAddress = new Uri(BaseUri);
        httpClient.DefaultRequestHeaders.Authorization =
            _authenticationHeaderValueCreator.CreateAuthenticationHeaderValue("bearer", accessToken);
    }

CreateHttpContent()

    public ByteArrayContent CreateHttpContent<TParam>(TParam httpObject)
    {
        var content = JsonConvert.SerializeObject(httpObject);
        var buffer = System.Text.Encoding.UTF8.GetBytes(content);
        var byteContent = new ByteArrayContent(buffer);

        byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        return byteContent;
    }

2 个答案:

答案 0 :(得分:0)

我敢打赌你的API Put方法确实会返回消息No route matches the supplied values的HTTP 500错误。你可以在Fiddler中查看。

问题在于以下几行:

var route = CreatedAtRoute("GetSchool", school);

CreatedAtRoute方法将路由名称作为第一个参数。我怀疑你有一条名为GetSchool的路线。它在同一个控制器中是一个动作名称。并且CreatedAtRoute不会为未知路由抛出异常,它只返回500个错误代码。

要解决此问题,请使用CreatedAtAction方法代替CreatedAtRoute

var route = CreatedAtAction("GetSchool", school);

答案 1 :(得分:0)

我认为问题是API的结果无法序列​​化。尝试在单元测试中自己手动序列化结果并查看它失败的位置。