无法实现Post方法操作并使用api?

时间:2019-04-02 13:15:21

标签: c# asp.net-mvc mongodb api asp.net-web-api

我正在使用Web API调用并实现一个post方法,以将值插入到MongoDB中。值无法插入。 应该将数据插入到MongoDB中已经创建的数据库中!我是Web API 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(Controller)

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(controller)

  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(查看)

@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")
}

我的错误的屏幕快照已附加 api[![api_four _ one ][1]] 3

api_three

1 个答案:

答案 0 :(得分:1)

client.BaseAddress = new Uri("http://localhost:61093/api/MongoDb/save")