1

我有以下场景:具有“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& $过滤器=类别 ID eq 12 "

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

提前致谢。

4

1 回答 1

3

您可以使用此帮助程序从请求中获取 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))));
    }
于 2013-03-18T20:51:28.753 回答