我们如何通过HttpClient使用Web API?

时间:2017-09-27 05:31:50

标签: asp.net-web-api

我使用.NET API来使用它。但是代码不起作用。你可以给我解决下面的代码吗?

// State object
List<SelectListItem> state = new List<SelectListItem>();

// Client            
HttpClient client1 = new HttpClient();
client1.BaseAddress = new Uri("http://localhost:2585/");

// JSON type
client1.DefaultRequestHeaders.Accept.Add(
    new MediaTypeWithQualityHeaderValue("application/json")
);

// Web API controller
var response1 = client1.GetAsync("api/State");

if (response1.IsSuccessStatusCode) // Response type
{
    state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
    return Json(state, JsonRequestBehavior.AllowGet);

1 个答案:

答案 0 :(得分:0)

        [HttpGet]
                public ActionResult Index()
                {
                    List<Student> EmpInfo = new List<Student>();
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri("http://localhost:2585/");

                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    var response = client.GetAsync("api/StudentApi").Result;

                    if (response.IsSuccessStatusCode)
                    {
                        EmpInfo = JsonConvert.DeserializeObject<List<Student>>(response.Content.ReadAsStringAsync().Result);
                        return View(EmpInfo);
                    }
                    return View();
                }

                [HttpGet]
                public PartialViewResult Edit(int id)
                {
                    StudentViewModel EmpInfo = new StudentViewModel();

                    HttpClient client1 = new HttpClient();
                    client1.BaseAddress = new Uri("http://localhost:2585/");

                    client1.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    var responsecountry = client1.GetAsync("api/Country/").Result;
                    List<SelectListItem> country = new List<SelectListItem>();


                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri("http://localhost:2585/");

                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    var response = client.GetAsync("api/StudentApi/" + id).Result;


                    if (response.IsSuccessStatusCode)
                    {
                        EmpInfo = JsonConvert.DeserializeObject<StudentViewModel>(response.Content.ReadAsStringAsync().Result);
                        if (responsecountry.IsSuccessStatusCode)
                        {
                            country = JsonConvert.DeserializeObject<List<SelectListItem>>(responsecountry.Content.ReadAsStringAsync().Result);
                            EmpInfo.Country = country;
                        }
                        return PartialView(EmpInfo);
                    }
                    return PartialView();
                }


                public ActionResult Create()
                {
                    StudentViewModel student = new StudentViewModel();
                    List<SelectListItem> country = new List<SelectListItem>();
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri("http://localhost:2585/");

                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    var response = client.GetAsync("api/Country/").Result;

                    List<SelectListItem> state = new List<SelectListItem>();
                    HttpClient client1 = new HttpClient();
                    client1.BaseAddress = new Uri("http://localhost:2585/");

                    client1.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    if (response.IsSuccessStatusCode)
                    {
                        country = JsonConvert.DeserializeObject<List<SelectListItem>>(response.Content.ReadAsStringAsync().Result);
                        student.Country = country;
                        var response1 = client1.GetAsync("api/State/" + Convert.ToInt32(country.FirstOrDefault().Value)).Result;
                        if (response1.IsSuccessStatusCode)
                        {
                            state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
                            student.State = state;
                        }
                    }

                    return View(student);
                }

                public JsonResult GetStates(int countryId)
                {
                    List<SelectListItem> state = new List<SelectListItem>();
                    HttpClient client1 = new HttpClient();
                    client1.BaseAddress = new Uri("http://localhost:2585/");

                    client1.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    var response1 = client1.GetAsync("api/State/" + countryId).Result;
                    if (response1.IsSuccessStatusCode)
                    {
                        state = JsonConvert.DeserializeObject<List<SelectListItem>>(response1.Content.ReadAsStringAsync().Result);
                        return Json(state, JsonRequestBehavior.AllowGet);
                    }
                    return Json(state);
                }

                [HttpPost]
                public ActionResult Create(Student student)
                {
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri("http://localhost:2585/");

                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = client.PostAsJsonAsync("api/StudentApi", student).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        return RedirectToAction("Index");
                    }
                    return null;
                }

                [HttpPost]
                public ActionResult Update(StudentViewModel student)
                {
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri("http://localhost:2585/");

                    client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));
                    var stu = new Student()
                    {
                        Id = student.Id,
                        FirstName = student.FirstName,
                        LastName = student.LastName,
                        DateOfBirth = student.DateOfBirth,
                        Email = student.Email,
                        Phone = student.Phone,
                        CountryId = student.CountryId
                    };
                    HttpResponseMessage response = client.PutAsJsonAsync("api/StudentApi/", stu).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        return RedirectToAction("Index");
                    }
                    return null;
                }

                [HttpPost]
                public JsonResult EmailExists(string email)
                {
                    return Json(!String.Equals(email, "h@h.com", StringComparison.OrdinalIgnoreCase));

                    //var user = Membership.GetUser(UserName);
                    //return Json(user == null);
                }
            }

    -----------
    Create
    -----------
    @model Practice.Web.Models.StudentViewModel
    @{
        ViewBag.Title = "Create";
    }

    <h2>Create</h2>
    <html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>SignUp</title>
        <script src="@Url.Content("~/Scripts/jquery-1.12.4.js")"></script>
        <script type="text/javascript">

            $(document).ready(function () {
            //Dropdownlist Selectedchange event
            $("#CountryId").change(function () {
                $("#StateId").empty();
                $.ajax({
                    type: 'GET',
                    url: '@Url.Action("GetStates")', // we are calling json method
                    dataType: 'json',
                    data: { countryId: $("#CountryId").val() },
                    success: function (state) {
                        //debugger;
                        $.each(state, function (i, s) {
                            $("#StateId").append('<option value="' + s.Value + '">' +
                             s.Text + '</option>');
                        });
                    },
                    error: function (ex) {
                        alert('Failed to retrieve states.' + ex);
                    }
                });
                return false;
            })
        });
        </script> 
        @section Scripts {
            @Scripts.Render("~/bundles/jqueryval")
        }



    </head>
    <body>
        @using (Html.BeginForm("Create", "Student", FormMethod.Post))
        {
            <table cellpadding="0" cellspacing="0">
                <tr>
                    <th colspan="2" align="center">Person Details</th>
                </tr>
                <tr>
                    <td>First Name: </td>
                    <td>
                        @Html.TextBoxFor(m => m.FirstName)
                    </td>
                </tr>
                <tr>
                    <td>Last Name: </td>
                    <td>
                        @Html.TextBoxFor(m => m.LastName)
                    </td>
                </tr>
                <tr>
                    <td>Date Of Birth: </td>
                    <td>
                        @Html.TextBoxFor(m => m.DateOfBirth)
                    </td>
                </tr>
                <tr>
                    <td>Email: </td>
                    <td>
                        @Html.TextBoxFor(m => m.Email)
                        @Html.ValidationMessageFor(model => model.Email)


                    </td>
                </tr>
                <tr>
                    <td>Phone: </td>
                    <td>
                        @Html.TextBoxFor(m => m.Phone)
                    </td>
                </tr>
                <tr>
                    <td>Country: </td>
                    <td>
                        @Html.DropDownListFor(m => m.CountryId, Model.Country)
                    </td>
                </tr>

                <tr>
                    <td>State: </td>
                    <td>
                        @Html.DropDownListFor(m => m.StateId, Model.State)
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Submit" /></td>
                </tr>
            </table>
        }
    </body>
    </html>
    -----------------
    Edit
    ---------------------
    @model Practice.Web.Models.StudentViewModel
    @{
        ViewBag.Title = "Edit";
    }


    <style>
        .button {
            background-color: #4CAF50; /* Green */
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
        }

        .button1 {
            border-radius: 2px;
        }

        .button2 {
            border-radius: 4px;
        }

        .button3 {
            border-radius: 8px;
        }

        .button4 {
            border-radius: 12px;
        }

        .button5 {
            border-radius: 50%;
        }
    </style>

    <div class="modal-body">
        @using (Ajax.BeginForm("Update", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "divEmp" }))
        {
            <table cellpadding="0" cellspacing="0">
                <tr>
                    <th colspan="2" align="center">Person Details</th>
                    @Html.HiddenFor(m => m.Id)
                </tr>
                <tr>
                    <td>First Name: </td>
                    <td>
                        @Html.TextBoxFor(m => m.FirstName)

                    </td>
                </tr>
                <tr>
                    <td>Last Name: </td>
                    <td>
                        @Html.TextBoxFor(m => m.LastName)
                    </td>
                </tr>
                <tr>
                    <td>Date Of Birth: </td>
                    <td>
                        @Html.TextBoxFor(m => m.DateOfBirth)
                    </td>
                </tr>
                <tr>
                    <td>Email: </td>
                    <td>
                        @Html.TextBoxFor(m => m.Email)
                        @Html.ValidationMessageFor(model => model.Email)


                    </td>
                </tr>
                <tr>
                    <td>Phone: </td>
                    <td>
                        @Html.TextBoxFor(m => m.Phone)
                    </td>
                </tr>
                <tr>
                    <td>Country: </td>
                    <td>
                        @Html.DropDownListFor(m => m.CountryId, Model.Country, new SelectListItem { Value = Model.CountryId.ToString() })
                    </td>
                </tr>
                <tr>
                    <td></td>
                    <td><input type="submit" value="Submit" id="btnHideModal" /></td>
                </tr>
            </table>
        }
    </div>
    <div class="modal-footer">
        <button type="submit" class="btn btn-primary button button4">Update</button>
        <button type="button" class="btn btn-primary button button4">
            Hide
        </button>
    </div>
    <script type="text/javascript">
        $(document).ready(function () {
            //$("#btnShowModal").click(function () {
            $("#loginModal").modal('show');
            //});

            $("#btnHideModal").click(function () {
                $("#loginModal").modal('hide');
            });
        });
    </script>
----------------------
Edit
---------------------
@model IEnumerable<Practice.Entity.Student>
@{
    ViewBag.Title = "Index";
}
<html>
<head>
    <script src="~/Scripts/jquery-1.12.4.js"></script>
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    @*<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
        <link href="@Url.Content("~/Content/themes/base/jquery-ui.min.css") rel=" stylesheet" type="text/css" />
        <script>
            $(document).ready(function () {

                //$(".editDialog").live("click", function (e) {
                $(".editDialog").click(function (e) {
                    debugger;
                    var url = $(this).attr('href');
                    $("#dialog-edit").dialog({
                        title: 'Edit Employee Detail',
                        autoOpen: false,
                        resizable: false,
                        height: 455,
                        width: 550,
                        show: { effect: 'drop', direction: "up" },
                        modal: true,
                        draggable: true,
                        open: function (event, ui) {
                            debugger;
                            $(this).load(url);

                        },
                        close: function (event, ui) {
                            $(this).dialog('close');
                        }
                    });

                    $("#dialog-edit").dialog('open');
                    return false;
                });
            });


        </script>*@



</head>
<body id="divEmp">
    <h2>Index</h2>
    @Html.ActionLink("Create Student", "Create", "Student")
    <div id="dialog-edit">
    </div>
    <table>
        <tr>
            <td>First Name</td>
            <td>Last Name</td>
            <td>DOB</td>

        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>@item.FirstName</td>
                <td>@item.LastName</td>
                <td>@item.DateOfBirth</td>
                <td>
                    @*@Html.ActionLink("Edit", "Edit", new { id = @item.Id }, new { @class = "editDialog" })*@
                    <a class="editDialog">Edit</a>

                </td>
            </tr>
        }


    </table>

    <div class="modal fade" tabindex="-1" id="loginModal"
         data-keyboard="false" data-backdrop="static">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        ×
                    </button>
                    <h4 class="modal-title">Satya Login</h4>
                    <div id="divHtml"></div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">

</script>

<script src="~/Scripts/bootstrap.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(".editDialog").click(function () {
            $("#loginModal").modal('show');
            $.ajax({
                url: '/Student/Edit/1',
                contentType: 'application/html; charset=utf-8',
                type: 'GET'
            })
            .success(function (result) {
                $('#divHtml').html(result);
            })
            .error(function (xhr, status) {
                alert(status);
            });

        });

        $("#btnHideModal").click(function () {
            $("#loginModal").modal('hide');
        });
    });
</script>