【发布时间】:2019-11-07 19:58:48
【问题描述】:
我正在构建一个 Web 应用程序来使用一个 REST FULL API ASP.Net 核心 Web 服务,我在更新记录时遇到问题。 我正在尝试通过 ASP.Net Core 应用程序从 API ASP.Net 核心调用 Put 方法
我遇到了 NullReferenceException:对象引用未设置为对象的实例。
public async Task<IActionResult> UpdateEmployee(int id)
{
Employee employee = new Employee();
using(var httpClient=new HttpClient())
{
using(var response = await httpClient.GetAsync("myURI/employee/" + id))
{
string apiResponse = await
response.Content.ReadAsStringAsync();
employee = JsonConvert.DeserializeObject<Employee>apiResponse);
}
}
return View(employee);
}
[HttpPost]
public async Task<IActionResult> UpdateEmployee(Employee employee)
{
Employee receivedemployee = new Employee();
using(var httpClient=new HttpClient())
{
var content = new MultipartFormDataContent();
content.Add(new
StringContent(employee.EmployeeId.ToString(),Encoding.UTF8,
"application/json"), "id");
content.Add(new
StringContent(employee.FirstName,Encoding.UTF8,
"application/json"),"FirstName");
content.Add(new StringContent(employee.LastName,
Encoding.UTF8, "application/json"), "LastName");
content.Add(new StringContent(employee.DateOfBirth.ToString(),
Encoding.UTF8, "application/json"), "Email");
content.Add(new StringContent(employee.PhoneNumber,
Encoding.UTF8, "application/json"), "DateOfBirth");
content.Add(new StringContent(employee.Email, Encoding.UTF8,
"application/json"), "Email");
using (var response = await httpClient.PutAsync("myURI/api/employee", content))
{
string apiResponse = await response.Content.ReadAsStringAsync();
ViewBag.Result = "Success";
receivedemployee = JsonConvert.DeserializeObject<Employee>(apiResponse);
}
return View(receivedemployee);
}
}
}
我希望更新记录
【问题讨论】:
-
你在哪一行得到错误?
-
我也不认为您需要使用响应...我将尝试清理您的代码并将其放入答案中
-
我的视图出现错误。
-
一切运行良好,但只有当我更新记录时我得到一个错误,当我暂停调试时响应变量值是 ={StatusCode: 405, ReasonPhrase: 'Method Not Allowed',版本:1.1等
-
myURI/employee/{id}这条路线..我能看到那个api端点的方法吗?
标签: asp.net-mvc api asp.net-core core-api