反序列化当前JSON数组以使用Web API执行编辑操作

时间:2019-04-03 10:41:30

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

我正在使用Web API编辑MongoDB中集合中的值。我添加了代码以从mongodb中获取值,并在另一个代码中调用了它以获取api以执行编辑功能。

我的ID正在传递给该操作,并且当我修复它时,仍然会出现null引用异常,反序列化会发生数组错误。我试图使用net中找到的代码对数组进行反序列化,但是没有成功!为什么会发生此错误?我是Web API和Mongo DB的新手!请帮忙!

Contact.cs(模型类)

public class Contact
{
    [BsonId]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
}

mongodbcontroller(Controller)

        [System.Web.Http.HttpPut]
            public Contact Edit(Contact contact)
            {
                var contactsList = mongoDatabase.GetCollection("contact");
                WriteConcernResult result;
                bool hasError = false;

                string errorMessage = string.Empty;
                try
                {
                    if (!string.IsNullOrEmpty(contact.Id))
                    {
                        IMongoQuery query = Query.EQ("Id", contact.Id);
                        IMongoUpdate update = MongoDB.Driver.Builders.Update
                            //.Set("Id",contact.Id)
                            .Set("Name", contact.Name)
                            .Set("Address", contact.Address)
                            .Set("Phone", contact.Phone)
                            .Set("Email", contact.Email);
                        result = contactsList.Update(query, update);
                        contactsList.Save(contact);

                        hasError = result.HasLastErrorMessage;
                    }
                }
                catch(Exception ex)
                {
                    errorMessage = ex.ToString();
                }


                if (!hasError)
                {
                    return contact;
                }
                else
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);
                }
            }

TestController(包含api)

     public ActionResult Edit(string id)
        {
            //Contact contact = new Contact();
            Contact contact = new Contact();
            try
            {
                using (var client = new HttpClient())
                {


                    client.BaseAddress = new Uri("http://localhost:61093/api/MongoDb/edit");
                    //HTTP GET
                    var responseTask = client.GetAsync("?id=" + id);
                    responseTask.Wait();

                    var result = responseTask.Result;

                    if (result.IsSuccessStatusCode)
                    {

                        var readTask = result.Content.ReadAsAsync<Contact>();
                        readTask.Wait();

                        contact = readTask.Result;
                    }
                }
            }
            catch (Exception ex)
            {

            }


            return View(contact);


        }

    [HttpPost]
    public ActionResult Edit(Contact contact)
    {

        try
        {
            using (var client = new HttpClient())
            {

                client.BaseAddress = new Uri("http://localhost:61093/api/MongoDb/edit");
                //HTTP GET
                var putTask = client.PutAsJsonAsync<Contact>("contact",contact);
                putTask.Wait();

                var result = putTask.Result;
                if (result.IsSuccessStatusCode)
                {
                    return RedirectToAction("Index");
                }                     
            }
        }
        catch (Exception ex)
        {

        }


        return View(contact);

    }

Edit.cshtml(查看)


    @model TestApi.Models.Contact

  @{
      ViewBag.Title = "Edit";
  }

  <h2>Edit</h2>


  @using (Html.BeginForm())
  {
      @Html.AntiForgeryToken()

      <div class="form-horizontal">
          <h4>Contact</h4>
          <hr />
          @Html.ValidationSummary(true, "", new { @class = "text-danger" })
          @Html.HiddenFor(model => model.Id)

          <div class="form-group">
              @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
              <div class="col-md-10">
                  @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                  @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
              </div>
          </div>

          <div class="form-group">
              @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
              <div class="col-md-10">
                  @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                  @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
              </div>
          </div>

          <div class="form-group">
              @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
              <div class="col-md-10">
                  @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                  @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
              </div>
          </div>

          <div class="form-group">
              @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
              <div class="col-md-10">
                  @Html.EditorFor(model => model.Phone, new { htmlAttributes = new { @class = "form-control" } })
                  @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })
              </div>
          </div>

          <div class="form-group">
              <div class="col-md-offset-2 col-md-10">
                  <input type="submit" value="Save" class="btn btn-default" />
              </div>
          </div>
      </div>
  }

  <div>
      @Html.ActionLink("Back to List", "Index")
  </div>

  @section Scripts {
      @Scripts.Render("~/bundles/jqueryval")
  }

我的代码的屏幕截图位于下面 1 2 3 4

0 个答案:

没有答案