从 Web 方法动态返回字段 [英] Dynamically return fields from a web method

查看:32
本文介绍了从 Web 方法动态返回字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WebAPI 服务,我希望允许用户指定他们想要返回的字段.例如,假设我有以下 Person 类:

I have a WebAPI service where I would like to allow users to specify which fields they'd like returned. For example, say I have the following Person class:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

并且调用 /api/people/ 会返回所有人的所有三个字段.我如何处理像 /api/people?fields=FirstName,Email 这样的请求,只为所有人返回这两个字段?如果我可以将诸如 first_name 之类的东西映射到 FirstName ,但那不是必需的.

and that calling /api/people/ returns all three fields for all people. How do I handle a request like /api/people?fields=FirstName,Email returning just those two fields for all people? Bonus points if I can map something like first_name to FirstName but that's not required.

推荐答案

这是动态语言运行时,特别是 ExpandoObject,这样你就只返回你需要的属性在运行时确定:

public dynamic GetPerson()
{
    bool firstNameRequired = true; // TODO: Parse querystring
    bool lastNameRequired = false; // TODO: Parse querystring

    dynamic rtn = new ExpandoObject();

    if (firstNameRequired)
        rtn.first_name = "Steve";

    if (lastNameRequired)
        rtn.last_name = "Jobs";

    // ... and so on

    return rtn;
}

void Main()
{
    // Using the serializer of your choice:
    Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(GetPerson()));
}

输出:

{"first_name":"Steve"}

{"first_name":"Steve"}

我现在没有办法测试它[我在 vanilla Web API 的生产中有类似的东西,有大量的可选字段],但是通过 .NET Core 文档,Web 方法看起来有点像就像这样,尽管没有硬编码值!:

I don't have the means to test it right now [I have something similar in production on vanilla Web API, with a large number of optional fields], but going by the .NET Core docs the web method would look something like this albeit without the hard coded values!:

[HttpGet()]
public IActionResult Get([FromQuery(Name = "fields")] string fields)
{
    var fieldsOptions = fields.Split(',');

    dynamic rtn = new ExpandoObject();

    if (fieldsOptions.Contains("FirstName"))
        rtn.first_name = "Steve";

    if (fieldsOptions.Contains("LastName"))
        rtn.last_name = "Jobs";

    if (fieldsOptions.Contains("Email"))
        rtn.email = "steve@apple.com";

    return new ObjectResult(rtn);
}

<小时>

您需要引用 System.Dynamic.Runtime 包.

这篇关于从 Web 方法动态返回字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆