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

查看:93
本文介绍了从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":史蒂夫"}

{"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天全站免登陆