Web API GET 允许 URI 中的字符串

Web API GET that allows strings in the URI

我缺少关于 ASP.net Web API 的一些基本信息。我想要一个从 GET:

中提取字符串的方法

/api/values/some+字符串+值

我将开箱即用的 GET api/values/5 更改为:

    public string Get([FromUri] string someString)
    {
        return "some return value";
    }

但我只收到 404。我遗漏了什么?

FromUri 是多余的,因为 GET 没有正文。

但要回答您的问题,我们需要将 someString 映射到 URI 的正确部分(在您的例子中,它是最后一个元素)。如果没有映射,客户端必须在 URL 中命名参数。因此,例如,这现在对您有用:

http://localhost:53865/api/values?somestring=foo

这很好,但是你想要这个:

http://localhost:53865/api/values/foo

你可能会想,"why does the default Get(int Id) work and not mine?"好吧,让我们看看solution.There的App_Start文件夹中的WebApiConfig,你应该会看到一些看起来像喜欢:

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

这将设置 WebApi 的默认路由,即 mywebsite。com/api/controller/id。只要您的控制器的操作遵循这个简单的命名约定,一切都会自动进行。现在,如果您使用的是 WebApi 1(您确实不应该用于新项目,但您可能基于您的评论),则需要在 before 添加一个新映射默认一个。类似于:

config.Routes.MapHttpRoute("SomeString", "api/{controller}/{someString}");

这曾经是唯一的方法,但现在几乎没有人这样做了。相反,我们使用 [Route()] 属性,它允许我们为每个单独的操作设置路由。因此,如果我们向您的路由属性添加路由属性,它将如下所示:

[Route("api/values/{someString}")]
public string Get(string someString)
{
    return "some return value";
}

这应该可以为您解决。 :)