【问题标题】:How do I return related entities in web api, and call web api from separate mvc application如何在 web api 中返回相关实体,并从单独的 mvc 应用程序调用 web api
【发布时间】:2018-09-12 07:04:29
【问题描述】:

如何在 Web API 方法中返回实体及其相关实体,并从 MVC 应用程序调用它。

我有一个 Web API,我在其中返回一个 Person 实体,我还返回所有链接到 Person 实体的策略。

所以Person 可以有一个或多个Policies。

到目前为止,我可以在我的 Web API 控制器中执行此操作。

问题是在单独的 MVC 应用程序中调用我的 Web API。

目前我只能在我的 MVC 应用程序中返回 Person 记录,我正在努力在我的 MVC 应用程序中返回 Person 和所有相关的 Policies。

在我的 MVC .cshtml 视图中,我正在调用 ViewModel 以将数据传递给 Web API 中的所有字段。

This is my WebApi Method

Web Api ViewModel

Policies Class

MVC Controller calling Web Api method

This is the mvc cshtml view I am displaying the data from the web api in

    [Route("{pklifeinsured}")]
    public IHttpActionResult GetRec(int pklifeinsured)
    {
        var model = new Amendments_Interface_VM();
        using (var db = new TestLiveEntities())
        {
            var ctx = db.LifeInsureds.Where(l => l.pkLifeInsured == pklifeinsured).FirstOrDefault();
            if (ctx != null)
            {
                model = new Amendments_Interface_VM
                {
                    pkLifeInsured = ctx.pkLifeInsured,
                    IdNumber = ctx.IdNumber,
                    Surname = ctx.Surname,
                    FirstName = ctx.FirstName,
                    Initials = ctx.Initials,
                    fkGender = ctx.fkGender,
                    DateOfBirth = ctx.DateOfBirth,
                    fkTitle = ctx.fkTitle,
                    fkMaritalStatus = ctx.fkMaritalStatus,
                    fkSmokerStatus = ctx.fkSmokerStatus,
                    fkLanguage = ctx.fkLanguage,
                    fkCommunicationMethod = ctx.fkCommunicationMethod,
                    Mobile = ctx.Mobile,
                    HomeTel = ctx.HomeTel,
                    EmailHome = ctx.EmailHome,
                    WorkTel = ctx.WorkTel,
                    EmailWork = ctx.EmailWork,
                    Postal_AddressLine1 = ctx.Postal_AddressLine1,
                    Postal_AddressLine2 = ctx.Postal_AddressLine2,
                    Postal_AddressLine3 = ctx.Postal_AddressLine3,
                    Postal_AddressLine4 = ctx.Postal_AddressLine4,
                    Postal_AddressLine5 = ctx.Postal_AddressLine5,
                    Physical_AddressLine1 = ctx.Physical_AddressLine1,
                    Physical_AddressLine2 = ctx.Physical_AddressLine2,
                    Physical_AddressLine3 = ctx.Physical_AddressLine3,
                    Physical_AddressLine4 = ctx.Physical_AddressLine4,
                    Physical_AddressLine5 = ctx.Physical_AddressLine5
                };
                model.PolicyHolder = db.PolicyHolders.Where(x => x.fkLifeInsured == pklifeinsured).Select(p => new PolicyHolderVM
                {
                    PolicyNumber = p.PolicyNumber,
                    DOC = p.DOC,
                    fkLifeInsured = p.fkLifeInsured,
                    PolicyStatus = p.PolicyStatus,
                    RelationshipToLifeInsured = p.RelationshipToLifeInsured,
                    Package = p.Package,
                    Name = p.Name,
                    ContactNumber = p.ContactNumber,
                    ID_Reg_Num = p.ID_Reg_Num,
                    EmailAddress = p.EmailAddress
                }).ToList();
            }
        }
        return Ok(model);
    }




public class Amendments_Interface_VM
{
    public int pkLifeInsured { get; set; }
    public string FirstName { get; set; }
    public string Initials { get; set; }
    public string Surname { get; set; }
    public string fkTitle { get; set; }
    public string fkGender { get; set; }
    public string IdNumber { get; set; }
    public Nullable<System.DateTime> DateOfBirth { get; set; }
    public string fkMaritalStatus { get; set; }
    public string fkSmokerStatus { get; set; }
    public string fkLanguage { get; set; }
    public string fkCommunicationMethod { get; set; }
    public string WorkTel { get; set; }
    public string Mobile { get; set; }
    public string EmailWork { get; set; }
    public string HomeTel { get; set; }
    public string EmailHome { get; set; }
    public string Postal_AddressLine1 { get; set; }
    public Nullable<int> PA1_Id { get; set; }
    public string Postal_AddressLine2 { get; set; }
    public Nullable<int> PA2_Id { get; set; }
    public string Postal_AddressLine3 { get; set; }
    public Nullable<int> PA3_Id { get; set; }
    public string Postal_AddressLine4 { get; set; }
    public Nullable<int> PA4_Id { get; set; }
    public string Postal_AddressLine5 { get; set; }
    public Nullable<int> PA5_Id { get; set; }
    public string Physical_AddressLine1 { get; set; }
    public Nullable<int> PhyA1_Id { get; set; }
    public string Physical_AddressLine2 { get; set; }
    public Nullable<int> PhyA2_Id { get; set; }
    public string Physical_AddressLine3 { get; set; }
    public Nullable<int> PhyA3_Id { get; set; }
    public string Physical_AddressLine4 { get; set; }
    public Nullable<int> PhyA4_Id { get; set; }
    public string Physical_AddressLine5 { get; set; }
    public Nullable<int> PhyA5_Id { get; set; }

    public IList<PolicyHolderVM> PolicyHolder { get; set; }

}




  public class PolicyHolderVM
{
    public int PolicyNumber { get; set; }
    public Nullable<System.DateTime> DOC { get; set; }
    public int fkLifeInsured { get; set; }
    public string PolicyStatus { get; set; }
    public string RelationshipToLifeInsured { get; set; }
    public string Package { get; set; }
    public string Name { get; set; }
    public string ContactNumber { get; set; }
    public string ID_Reg_Num { get; set; }
    public string EmailAddress { get; set; }
}


        public ActionResult Index(int? pklifeinsured)
    {
        var LifePolicy = new Amendments_Interface_VM();

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(apiURL);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.GetAsync($"{apiURL}/api/LifePol/{pklifeinsured}").Result;

            if (response.IsSuccessStatusCode)
            {
                LifePolicy = response.Content.ReadAsAsync<Amendments_Interface_VM>().Result;
            }
        }
        return View(LifePolicy);
    }

@model WebApiTest_Invoke.Models.Amendments_Interface_VM

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<div class="panel-group" id="MainScreen">

    <div class="panel panel-default">
        <div class="panel-heading">
            <a data-toggle="collapse" data-parent="#MainScreen" href="#collapse1"><strong>Policy Holder/s</strong></a>
        </div>
    </div>
    <div id="collapse1" class="panel-collapse collapse in">
        <div class="panel-body">
            <table class="table table-bordered">
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.PolicyNumber)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.PolicyNumber)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.DOC)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.DOC)
                    </td>
                </tr>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.fkLifeInsured)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.fkLifeInsured)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.PolicyStatus)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.PolicyStatus)
                    </td>
                </tr>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.RelationshipToLifeInsured)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.RelationshipToLifeInsured)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.Package)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.Package)
                    </td>
                </tr>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Name)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.Name)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.ContactNumber)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.ContactNumber)
                    </td>
                </tr>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.ID_Reg_Num)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.ID_Reg_Num)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.EmailAddress)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.EmailAddress)
                    </td>
                </tr>
                <tr>
                </tr>
            </table>
        </div>
    </div>



    <div class="panel panel-default">
        <div class="panel-heading">
            <a data-toggle="collapse" data-parent="#MainScreen" href="#collapse2"><strong>Life Insured</strong></a>
            <h3 class="panel-title">
                @using (Html.BeginForm("Index", "LifePol", FormMethod.Get))
                {
                    <p style="padding-left:700px;">
                        Policy Number: @Html.TextBox("pklifeinsured")
                        <input type="submit" value="Search" />
                    </p>
                }
            </h3>
        </div>
    </div>
    <div id="collapse2" class="panel-collapse collapse in">
        <div class="panel-body">
            <table class="table table-bordered">
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.Surname)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.Surname)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.fkGender)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.fkGender)
                    </td>
                </tr>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.FirstName)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.FirstName)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.fkSmokerStatus)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.fkSmokerStatus)
                    </td>
                </tr>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.fkTitle)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.fkTitle)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.DateOfBirth)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.DateOfBirth)
                    </td>
                </tr>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.IdNumber)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.IdNumber)
                    </td>
                    <th>
                        @Html.DisplayNameFor(model => model.Mobile)
                    </th>
                    <td>
                        @Html.DisplayFor(model => Model.Mobile)
                    </td>
                </tr>
                <tr>
                </tr>
            </table>
        </div>
    </div>
</div>
  public Amendments_Interface_VM HttpClientCall(Amendments_Interface_VM value, string uri, int? pklifeinsured)
    {
        var client = new HttpClient { BaseAddress = new Uri(apiURL) };
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var httpresult = client.GetAsync(apiURL).Result;

        if(httpresult.IsSuccessStatusCode)
        {
            var result = httpresult.Content.ReadAsStringAsync().Result;
            var data = JsonConvert.DeserializeObject<Amendments_Interface_VM>(result);
            return data;
        }

        return new Amendments_Interface_VM();
    }

error

【问题讨论】:

  • 嗨,伙计,欢迎来到 SO! :) 您可以将代码添加到问题中吗?图片让人很难弄清楚发生了什么:)
  • 嗨@garfbradaz,我也包含了代码。

标签: c# asp.net-mvc asp.net-web-api2


【解决方案1】:

我认为您可以在 mvc 应用程序中创建如下模型,然后调用 api

public class YourModel
{
    public Person Person{get;set;}
    public List<Policy> Policies {get;set;}
}

然后制作webapi方法以和model一样的格式发送数据,或者你甚至可以在webapi中使用同样的model来发送数据。

现在在您的 webapi 控制器中:

YourModel data=new YourModel();
Person person=new Person();
person.name="test name";
.
.
data.Person=person;
Policy policy1=new Policy();
policy1.name="test name";
.
.
Policy policy2=new Policy();
policy2.name="test name 2";
.
.
data.Policies.Add(policy1);
data.Policies.Add(policy2);

return Ok(data);

希望对你有帮助:)

【讨论】:

    【解决方案2】:

    您可以在您的 Person 模型中拥有 Policies 属性,并使用必要的操作对其进行填充。你的模型应该看起来像这样。您可以通过在模型中具有实体属性来返回所有相关实体。

        public class Person
        {
            /* public int Id { get; set; }
             * Other properties 
             */
    
            public List<PolicyHolderVM> policiesLst { get; set; }
        }
    

    我创建了调用 API 的函数。这将返回来自 API 的 Person 对象。

        public Person HttpClientCall(Person value, string uri)
        {
            var client = new HttpClient { BaseAddress = new Uri(_baseUrl) };
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            var httpresult = client.GetAsync(uri).Result;
    
            if (httpresult.IsSuccessStatusCode)
            {
                var result = httpresult.Content.ReadAsStringAsync().Result;
                var data = JsonConvert.DeserializeObject<Person>(result);
                return data
            }
    
            return new Person();
        }
    

    【讨论】:

    • 嗨@Aunell,我已经在我的WebApi项目中这样做了,它工作正常。现在我在一个未连接到数据库的单独MVC项目中调用WebApi项目,所以我需要一个 ViewModel,用于传递来自 WebApi 的所有数据,并将其显示在 MVC cshtml 视图中。
    • 嗨@Auneell,请看我上面的代码,我希望这会给你关于我的问题的更好信息
    • @ZUKISABHOLOSHA 您需要在 MVC 项目中具有相同的类结构。 API 将以 JSON 格式返回您的数据,因此使用 NewtonSoft 包将 JSON 转换为您的对象,例如“Movie m = JsonConvert.DeserializeObject(json);”
    • 我不确定上面的代码会去哪里。是在我看来还是 mvc 控制器。您能否根据上述代码结构举个例子....我问的原因是因为应用程序将 Person 数据返回到我的 mvc 视图,而不是 Policy 信息。
    • @ZUKISABHOLOSHA 我已经更新了我的答案。请看一下,让我知道这是否适合您。
    猜你喜欢
    • 2016-07-02
    • 1970-01-01
    • 2011-11-22
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-04-22
    • 2015-06-06
    • 2015-04-07
    相关资源
    最近更新 更多