根据字符串获取元素

Get element based on string

我正在使用 mvc 6 创建一个 Web api。现在我正在尝试从我的数据库中获取一个元素。 table 中的关键是一个字符串(电子邮件地址)。我无权访问此数据库,因此无法更改此 table.

的密钥

现在,在创建演示网站时api,我能够创建一个控制器来根据一个 int 键提取项目。但是,当试图通过字符串获取元素时,程序崩溃了。

    [Route("api/[controller]")]
    public class TodoController : Controller
    {    

        [HttpGet("{id:string}", Name = "GetByIdRoute")]
        public IActionResult GetById (string id)
        {
            var item = _items.FirstOrDefault(x => x.Id == id);
            if (item == null)
            {
                return HttpNotFound();
            }

            return new ObjectResult(item);
        }
   }

当尝试访问此路径(示例。com/api/Todo/key)键是字符串时,我在 startup.cs

中遇到异常

浏览器中的异常显示为:

System.InvalidOperationException The constraint entry 'id' - 'string' on the route 'api/Todo/{id:string}' could not be resolved by the constraint resolver of type 'DefaultInlineConstraintResolver'.

startup.cs 代码中断的部分是:

// Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });   

            });

我似乎无法弄清楚为什么不允许我通过字符串键获取项目。 这甚至可能吗?如果可以,我做错了什么?

只需删除 :string。无论如何,您并没有真正限制 id 的值 - 它已经是 URL.

中的一个字符串

This fairly old blog post 列出了可用的约束 - 你可以看到没有 :string 约束,因为你不需要那里。

约束用于为“更具体”的约束赋予优先级 - 例如“如果 URL 的那部分是 DateTime 的字符串表示形式,请使用这条路线” - 但由于一切都是字符串(在 URL 中),因此没有任何限制如果你明白我的意思,:string 会比它更具体。