将查询字符串参数附加到对象的 URL 的最佳方法

Best way to append query string parameter to URL from object

我有查询字符串 class.

  public class PagingModel
    {
        public int PageNumber { get; set; } = 1;
       
        public string Filter { get; set; } = "text";
    }

string url = "Menu/GetMenus";

我必须根据 ASP.NET Core 5 预览中的对象生成带有查询字符串的 URI。有没有内置的查询助手?

所需输出:

/Menu/GetMenus?PageNumber=3&Filter=text

MVC 控制器:

 public async Task<IActionResult> index_partial([FromQuery] PagingModel paging)
            {
              
                var data = await _apiService.GetMenusAsync(paging);
    
                return PartialView("_IndexPartial", data);
            }

服务:

   public async Task<PagedList<MenuModel>> GetMenusAsync(PagingModel paging)
            {
                string Requiredurl = "Menu/GetMenus?page="+ paging.PageNumber;
               
            }

有了这么简单的查询字符串,我会做

PagingModel qsData = new PagingModel();

//set qsData properties as needed 

string urlWithQueryString = $"/Menu/GetMenus?{nameof(PagingModel.PageNumber)}={qsData.PageNumber}&nameof(PagingModel.Filter)}={qsData.Filter}";

然而更标准的是做类似

的事情
string urlWithQueryString = this.Url.Action("GetMenus", "Menu", new PagingModel { PageNumber = 3, Filter = "text" }, this.Request.Url.Scheme);

但最佳解决方案取决于您的具体情况 - 您可以为 GetMenus 添加操作方法定义吗?

更新您的附加代码:

看起来你想在服务中生成 url 我会简单地这样做:

  public async Task<PagedList<MenuModel>> GetMenusAsync(PagingModel paging)
            {
                string Requiredurl =  $"/Menu/GetMenus?{nameof(PagingModel.PageNumber)}={paging.PageNumber}&nameof(PagingModel.Filter)}={paging.Filter}";

            }

我得到了这个扩展方法。不需要生成我们需要传递的查询字符串 manually.Only class 对象。我以为其他人可以使用同样的东西...

public static string AppendObjectToQueryString(string uri, object requestObject)
        {
            var type = requestObject.GetType();
            var data = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .ToDictionary
                (
                    p => p.Name,
                    p => p.GetValue(requestObject)
                );

            foreach (var d in data)
            {
                if (d.Value == null)
                {
                    continue;
                }

                if ((d.Value as string == null) && d.Value is IEnumerable enumerable)
                {
                    foreach (var value in enumerable)
                    {
                        uri = QueryHelpers.AddQueryString(uri, d.Key, value.ToString());
                    }
                }
                else
                {
                    uri = QueryHelpers.AddQueryString(uri, d.Key, d.Value.ToString());
                }
            }

            return uri;
        }

例如:在我的例子中,我是这样调用的。

string uri = "Menu/GetMenus";
 string full_uri = QueryStringExtension.AppendObjectToQueryString(uri, paging);