从MVC控制器中的Web API调用PUT方法

时间:2018-10-27 07:57:58

标签: asp.net-web-api asp.net-core-mvc

我为Web API和asp.net核心应用程序创建了两个项目。 我想在我的应用程序中实现Web api。

我的网络api中的“ PUT”方法:

    [Consumes("application/json")]
    [HttpPut]
    public async Task<IActionResult> PUT(Employee employee)
    {
        try
        {

            await employeeRepository.UpdateEmployeeByProperty(
                               employee, e => e.FirstName, 
                               e => e.MiddleName, e => e.LastName, 
                               e => e.DateOfBirth, e => e.ContactNo, 
                               e => e.EmailId, e => e.HighestQualification, 
                               e => e.TypeOfEmployee, e => e.Gender, 
                               e => e.StartDate, e => e.EndDate);
            if (await employeeRepository.SaveChangesAsync())
            {
                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception)
        {
            return BadRequest();
        }
    }

并且我正在使用以下代码在我的应用程序中调用上述方法:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EditEmployee(Employee employeeModel,string email,int id)
{
    var UserWithSameEmail = (Employee)null;
    if(employeeModel.EmailId!=email)
        UserWithSameEmail = _dbContext.Employee
                .Where(e => e.EmailId == employeeModel.EmailId).SingleOrDefault();
    if (ModelState.IsValid)
    {
        employeeModel.UpdatedDate = DateTime.Now;
        if (UserWithSameEmail == null)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:50822");
            var json = JsonConvert.SerializeObject(employeeModel);
            HttpResponseMessage response = client
                                .PutAsJsonAsync("api/employee",json).Result;
            if (response.IsSuccessStatusCode)
            {
                 TempData["msg"] = "" + employeeModel.EmailId + " updated successfully";
                ModelState.Clear();
            }
        }
        else
        {
            ModelState.AddModelError("EmailId", "Email Id already exists");
        }
    }
    return View("_EditEmployeePartial", employeeModel);
}

但是当我运行该应用程序时,我收到了状态码为400的错误

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: 
System.Net.Http.HttpConnection+HttpConnectionResponseContent, Headers:
{
   Server: Kestrel
   X-SourceFiles: =?UTF-8?B? RjpcQyBQYXJ0aXRpb25cRG9jdW1lbnRzXFRlamFzIFRyYWluaW5nXEVtcGxveWVlTWFuYWdlbWVudFN5c3RlbVxFbXBsb3llZU1hbmFnZW50LldlYlxXZWJBUElcYXBpXGVtcGxveWVl?=
   X-Powered-By: ASP.NET
   Access-Control-Allow-Origin: *
   Access-Control-Allow-Headers: Content-Type
   Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
   Date: Sat, 27 Oct 2018 07:54:27 GMT
   Content-Length: 0
}}

请帮助我解决这个问题... !!!

1 个答案:

答案 0 :(得分:0)

  1. 正如@ B12Toaster所说的那样:

    HttpResponseMessage响应= client.PutAsJsonAsync(“ api / employee”,json).Result; 应该阅读

    HttpResponseMessage响应=等待客户端。PutAsJsonAsync(“ api / employee”,json);

当您使用.Result时,容易出现令人讨厌的死锁;

  1. 您有两个return BadRequest();语句,如果您要返回400,那是因为您肯定要击中其中一个语句。我猜您需要对其进行调试,以找出原因。

  2. 此:

    catch (Exception)
    {
        return BadRequest();
    }
    

应该不是return InternalServerError();,以便您的调用应用程序知道出了什么问题。您可能还应该将此异常记录在某处,以便您了解发生了什么。

  1. 为什么这是BadRequest?

    如果(等待employeeRepository.SaveChangesAsync()) {    返回Ok(); } 其他 {    返回BadRequest(); }

在处理或保存数据之前,您应该先检查Employee,以确保在实际执行保存或处理之前可以成功进行处理或保存,并立即返回BadRequest,然后在处理{{1 }} 应该管用。我们称之为验证;-)

如果您查看所有这些点,那么您将更接近寻找答案。