2017-12-03 244 views
0

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

我不知道什么错误,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); 
     } 
    } 

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

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; 
    } 

回答

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); 
0

我认为这个问题是从API的结果是失败的序列化。尝试在单元测试中手动序列化结果并查看失败的位置。

相关问题