Я использую веб-API для вызова и реализации метода post для вставки значений в MongoDB.Значения не могут быть вставлены.Предполагается, что данные будут вставлены в уже созданную базу данных в MongoDB!Я новичок в веб-приложении MongoDB. Мне нужна помощь
Я написал код для вставки значений в «контакт» Коллекции. Код для использования API работает, но код для выполнения публикации - нет.Соединение установлено, но значение id не может быть вставлено.
**API code**
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 (контроллер)
public class MongoDbController : ApiController
{
readonly MongoDatabase mongoDatabase;
public MongoDbController()
{
mongoDatabase = RetreiveMongohqDb();
}
private MongoDatabase RetreiveMongohqDb()
{
MongoClient client = new MongoClient("mongodb://localhost:27017");
MongoServer server = client.GetServer();
return server.GetDatabase("mydb");
}
[System.Web.Http.HttpPost]
public Contact Save(Contact contact)
{
var contactsList = mongoDatabase.GetCollection("contact");
WriteConcernResult result;
bool hasError = false;
if (string.IsNullOrEmpty(contact.Id))
{
contact.Id = ObjectId.GenerateNewId().ToString();
result = contactsList.Insert<Contact>(contact);
contactsList.Save(contact);
hasError = result.HasLastErrorMessage;
}
if (!hasError)
{
return contact;
}
else
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
**Consuming API**
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; }
}
TestController (контроллер)
public class TestController : Controller
{
public ActionResult create()
{
return View();
}
[HttpPost]
public ActionResult create(Contact contact)
{
using (var client = new HttpClient())
{
//HTTP POST
var postTask = client.PostAsJsonAsync<Contact>("contact", contact);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
return RedirectToAction("Index");
}
}
//ModelState.AddModelError(string.Empty, "Server Error. Please contact administrator.");
return View(contact);
}
}
}
Create.cshtml (View)
@model TestApi.Models.Contact
@{
ViewBag.Title = "create";
}
<h2>create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Contact</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<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="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
Скриншоты моей ошибки прилагается
_one
] 3
![api_three](https://i.stack.imgur.com/yUBGy.png)