REST的WebAPI URI GET与字符串,而不是ID无法按预期的路由 [英] REST webapi URI GET with string instead of id not routing as expected

查看:283
本文介绍了REST的WebAPI URI GET与字符串,而不是ID无法按预期的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例,其中请求的http:// {}域/ API /富/ {用户名} 但我得到一个404状态code背部。没有其他的动作获得此控制器上存在。不应该这项工作?

 公共类FooController的:ApiController
{
    公共美孚获取(字符串的用户名)
    {
      返回_service.Get<富>(用户名);
    }
}


解决方案

在默认情况下你的路线将是这个样子:

  config.Routes.MapHttpRoute(
    名称:DefaultApi
    routeTemplate:API / {}控制器/(编号),
    默认:新{ID = RouteParameter.Optional}
);

当您访问的网址的http:// {}域/ API /富/ {用户名} 控制器被映射为和可选的 ID 参数映射到 {用户名} 。当你没有获取的操作方法与一个叫 ID 则返回404。

参数

要解决这个问题,你可以通过改变URL调用API方法更明确一些参数名称:

 的http:// {}域/ API / foo的用户名= {用户名}

或者你可以在你的操作方法更改参数名:

 公共美孚获取(字符串ID)
{
    无功富= _service.Get<富>(用户名);
    返回foo的;
}

或者你可以改变你的路线,接受用户名

  config.Routes.MapHttpRoute(
    名称:DefaultApi
    routeTemplate:API / {控制器} / {用户名},
    默认:新{用户名= RouteParameter.Optional}
);

I have the following example where the request is http://{domain}/api/foo/{username} but I get a 404 status code back. No other Get actions exist on this controller. Shouldn't this work?

public class FooController : ApiController
{
    public Foo Get(string username)
    {
      return _service.Get<Foo>(username);
    }
}

解决方案

By default your route will look something like this:

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

When you visit the url http://{domain}/api/foo/{username} the controller is mapped as foo and the optional id parameter is mapped to {username}. As you don't have a Get action method with a parameter called id a 404 is returned.

To fix this you can either call the API method by changing the URL to be explicit about the parameter name:

http://{domain}/api/foo?username={username}

Or you could change your parameter name in your action method:

public Foo Get(string id)
{
    var foo = _service.Get<Foo>(username);
    return foo;
}

Or you could change your route to accept a username:

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

这篇关于REST的WebAPI URI GET与字符串,而不是ID无法按预期的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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