【问题标题】:How to pass OData query parameters from one action to anoter via in a Redirect如何通过重定向将 OData 查询参数从一个操作传递到另一个操作
【发布时间】:2013-03-19 04:51:28
【问题描述】:

我有以下场景:带有“GetAll”方法的 ProductsController,它接受 ODataQueryOptions,如下所示:

    [GET("Products", RouteName = "GetAllProducts")]
    public ProductDTO[] Get(ODataQueryOptions options)
    {  
       //parse the options and do whatever...
        return new ProductDTO[] { };
    }

还有一个具有 GetProducts 方法的 CategoryController,如下所示:

    [GET("Category/{id}/Products", RouteName = "GetProductsByCategory")]
    public HttpResponseMessage GetProducts(int id, ODataQueryOptions options)
    {
        //Request URL can be "api/Category/12/Products?$select=Name,Price&$top=10"
        //Need to do a redirect the ProductsController "GetAllProducts" action
        HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
        msg.Headers.Location = new Uri(Url.Link("GetAllProducts",options));
        // how do we send the odata query string"$select=Name,Price&$top=10"
        //to the ProductsController? passing "options" directly does not work!
        return msg;
    }

我不想重新定义在 CategoryController 中按特定类别获取产品的逻辑。 有没有办法

1) 将 ODataQueryOptions 作为重定向的一部分传递?

2) 可以修改选项以添加额外的过滤条件吗?在上面的示例中,我想在执行重定向之前为当前 CategoryID 添加一个附加过滤条件,以便“GetAllProducts”接收以下请求: "api/Products?$select=Name,Price&$top=10&$filter=CategoryID eq 12"

以上是否有意义,或者我应该以不同的方式处理这个问题?

提前致谢。

【问题讨论】:

  • 您有需要重定向的原因吗?你能在两个控制器之间共享查找逻辑吗?
  • 我可以,但我希望避免代码重复。如果 DRY 将是在这里实现的 PITA,我将退回共享查找逻辑

标签: asp.net-web-api asp.net-web-api-routing


【解决方案1】:

您可以使用此帮助程序从请求中获取 OData 查询字符串。

    private static string GetODataQueryString(HttpRequestMessage request)
    {
        return
            String.Join("&", request
                                .GetQueryNameValuePairs()
                                .Where(kvp => kvp.Key.StartsWith("$"))
                                .Select(kvp => String.Format("{0}={1}", kvp.Key, Uri.EscapeDataString(kvp.Value))));
    }

【讨论】:

  • 这很好,但是如何在重定向中传递它?请注意,我使用“Url.Link”来获取基于上述代码示例中的路由名称的 url,该路由名称又用于在“msg.Headers.Location”中设置位置。
  • 只需将此附加到由链接方法生成的uri。确保将其附加为查询字符串。
猜你喜欢
  • 2012-01-13
  • 1970-01-01
  • 2013-12-27
  • 2020-04-07
  • 1970-01-01
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多