asp.net网页API路由不工作 [英] asp.net Web Api routing not working

查看:132
本文介绍了asp.net网页API路由不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的路由配置:

  config.Routes.MapHttpRoute(
    名称:ActionApi
    routeTemplate:API / {控制器} / {行动} / {ID}
    默认:新{ID = RouteParameter.Optional}
);

和,这里是我的控制器:

 公共ProductsController类:ApiController
{
    的[AcceptVerbs(获取)]
    公共对象的GetProducts()
    {
       //返回所有的产品...
    }    的[AcceptVerbs(获取)]
    公共对象产品(字符串名称)
    {
       //返回产品具有给定名称...
    }
}

当我尝试 API /产品/的GetProducts / ,它的工作原理。 API /产品/产品?名称=测试也可以,但是 API /产品/产品/测试不起作用。我在做什么错了?

更新:

下面就是我得到的,当我尝试 API /产品/产品/测试

  {
  消息:没有HTTP资源发现,请求URI的http://本地主机:42676 / API /产品/产品/测试相匹配。
  MessageDetail:没有采取任何控制器产品与请求匹配上找到。
}


解决方案

这是因为你的路由设置,它的默认值。你有两个选择。

1)通过改变路径设置以匹配产品()的参数来匹配的URI。

  config.Routes.MapHttpRoute(
    名称:ActionApi
    routeTemplate:API / {控制器} / {行动} / {name}的,//去掉标识和使用的名称
    默认:新{名= RouteParameter.Optional}
);

2)其他与推荐的方式是使用正确的方法签名属性。

 公共对象产品([FromUri(NAME =ID)字符串名){
       //用给定的名称返回产品
}

这是因为请求时,该方法需要一个参数的标识
API /产品/产品/测试的,而不是寻找的名称参数。

Here is my routing configuration:

config.Routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

And, here is my controller:

public class ProductsController : ApiController
{
    [AcceptVerbs("Get")]
    public object GetProducts()
    {
       // return all products...
    }

    [AcceptVerbs("Get")]
    public object Product(string name)
    {
       // return the Product with the given name...
    }
}

When I try api/Products/GetProducts/, it works. api/Products/Product?name=test also works, but api/Products/Product/test does not work. What am I doing wrong?

UPDATE:

Here's what I get when I try api/Products/Product/test:

{
  "Message": "No HTTP resource was found that matches the request URI 'http://localhost:42676/api/Products/Product/test'.",
  "MessageDetail": "No action was found on the controller 'Products' that matches the request."
}

解决方案

This is because of your routing settings and its default values. You have two choices.

1) By changing the route settings to match the Product() parameter to match the URI.

config.Routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{name}", // removed id and used name
    defaults: new { name = RouteParameter.Optional }
);

2) The other and recommended way is to use the correct method signature attribute.

public object Product([FromUri(Name = "id")]string name){
       // return the Product with the given name
}

This is because the method is expecting a parameter id when requesting api/Products/Product/test rather than looking for a name parameter.

这篇关于asp.net网页API路由不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆