通配符的WebAPI路径模板 [英] Wildcard in WebAPI Route template

查看:446
本文介绍了通配符的WebAPI路径模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了一个路径模板:

I have set up a route template:

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

控制器的操作签名:

controller's action signature:

public IEnumerable<object> Get(Int64 id,string abc)

我试图用URL http://mymachine.com/api/Individuals与之匹敌/ 1?ABC = 4 ,但它给了我一个异常

{的$ id:1,消息:错误有
  发生,ExceptionMessage:对象未设置为一个实例
  的
  对象,ExceptionType。:System.NullReferenceException,堆栈跟踪:
  在
  System.Web.Http.ValueProviders.Providers.RouteDataValueProvider.d__4.MoveNext(个)\\ r \\ n

{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":" at System.Web.Http.ValueProviders.Providers.RouteDataValueProvider.d__4.MoveNext()\r\n

奇怪的是, http://mymachine.com/api/Individuals?id= 1安培; ABC = 4 不匹配的控制器,操作和参数

Strangely, http://mymachine.com/api/Individuals?id=1&abc=4 does match with the controller,action and parameters.

我想: {ID} 的API / {}控制器/ {ID} / {*}通配符会工作。

I thought "{id}" of "api/{controller}/{id}/{*wildcard}" will work.

为什么?

推荐答案

通配符会告诉路由引擎的URI的其余部分匹配的路由参数(示例,请参见获取图书出版日期一节<一个href=\"http://www.asp.net/web-api/overview/web-api-routing-and-actions/create-a-rest-api-with-attribute-routing\"相对在这篇文章 =nofollow的>)。

The wildcard will tell the routing engine to match the rest of the URI to a route parameter (for an example, see "Get Books By Publication Date" section in this article).

这并不意味着任意命名变量匹配到任何参数 - 这是一件在默认情况下项目的查询字符串的WebAPI做你的路由配置,无论(所以为什么你第二个URI的工作 - 它没有匹配的路由)。

It does not mean match any arbitrary named variable to any parameter - this is something WebApi does by default with items on the querystring regardless of your route configuration (hence why you second URI worked - it didn't match any route).

这不匹配 {ID} 在你的路线,因为它期待一个名为 {通配符} 该参数没有标记为可选的。

It did not match {id} in your route because it was expecting a parameter called {wildcard} that was not marked as optional.

要说明,如果你只是改变'通配符'到'ABC':

To illustrate, if you simply changed 'wildcard' to 'abc':

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

然后,它会成功匹配以下URI:

Then it would successfully match the following URI:

http://mymachine.com/api/Individual/1/a/ b / C

通过值 ID = 1,ABC = A / B / C

要解决,只需从你的路线删除通配符,所以它看起来是这样的:

To fix, simply remove the wildcard from your route, so that it looks like this:

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

这篇关于通配符的WebAPI路径模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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