【问题标题】:How do I set param to FromURI using URL?如何使用 URL 将参数设置为 FromURI?
【发布时间】:2013-12-12 18:22:25
【问题描述】:

所以我有以下控制:

public class ItemQuery {
    public int storeID { get; set; }
    public int companyID { get; set; }
    public string itemName { get; set; }
    public string itemDescription { get; set; }
    public string itemPLU { get; set; }
    public string itemUPC { get; set; }
    public int supplierID { get; set; }
    public string partNumber { get; set; }
}
public class ItemController : ApiController {
    public List<Item> FindItem([FromUri]ItemQuery query) {
        return new List<Item>();
    }

}

我正在尝试用这个请求来解决它:

http://localhost:43751/api/Item/Find?query[storeID]=1

它不起作用,但给了我这个错误:

The requested resource does not support http method 'GET'.

我该怎么办?这是我的路由信息​​,我还没有更改任何内容:

    public static void RegisterRoutes(RouteCollection routes) {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

【问题讨论】:

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


    【解决方案1】:

    我认为您应该确保您使用 System.Web.Http 命名空间作为 Web Api。

    然后将方法名改为GetFindItem或添加HttpGet属性,如下:

    [HttpGet]
    public List<Item> FindItem([FromUri]ItemQuery query){  //   }
    

    此外,您的查询字符串应如下所示:

    http://localhost:43751/api/Item/?storeId=1&companyID=2&itemName=ABC&itemDescription=good&itemPLU=aa&itemUPC=dd&&supplierID=1&partNumber=number 
    

    如果您使用 Ajax 调用 Web API,下面是一个示例

    Js 文件

    var data = {
        storeID: 1,
        companyID: 1,
        itemName: 'Test',
        itemDescription: 'Description',
        itemPLU: 'Test',
        itemUPC: 'Test',
        supplierID: 1,
        partNumber: 'Description',
    };
    $.getJSON('/api/Item', { query:data }, function() {
           alert("success");
    });
    

    【讨论】:

      【解决方案2】:

      您尚未为 WebApi 定义路由。

      您拥有的 routes.MapRoute 用于 MVC。要为 WebApi 定义路由,您需要使用 routes.MapHttpRoute

      【讨论】:

        猜你喜欢
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-20
        • 2017-12-23
        • 1970-01-01
        相关资源
        最近更新 更多