简体   繁体   English

ASP.NET CORE、Web API:没有路由与提供的值匹配

[英]ASP.NET CORE, Web API: No route matches the supplied values

PLEASE NOTE: This question was asked in 2016. The original answer to this problem was to update the microsoft api versiong package.<\/strong>请注意:这个问题是在 2016 年提出的。这个问题的原始答案是更新 microsoft api versiong 包。<\/strong> In the current days, the problem reoccurs, but for other reasons.<\/strong>目前,该问题再次出现,但出于其他原因。<\/strong>

Original Question:原始问题:


i have some problems with the routing in asp.net core (web api).我在asp.net core(web api)中的路由有一些问题。

I have this Controller (simplified):我有这个控制器(简化):

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[Controller]")]
public class DocumentController : Controller
{

[HttpGet("{guid}", Name = "GetDocument")]
public IActionResult GetByGuid(string guid)
{
    var doc = DocumentDataProvider.Find(guid);
    if (doc == null)
        return NotFound();

    return new ObjectResult(doc) {StatusCode = 200};
}


[HttpPost]
public IActionResult Create([FromBody] Document doc)
{
    //... Creating Doc

    // Does not work   
    var val = CreatedAtRoute("GetDocument", new {guid = doc.Guid.ToString("N")}, document);

    // or this: 
    CreatedAtRoute("GetDocument", new { controller = "Document", guid = doc.Guid.ToString("N")}, document);
    // neither this
    var val = CreatedAtRoute("GetDocument", new { version = "1", controller = "Document", guid = doc.Guid.ToString("N")}, document);

    return val;
}
}

I know this post is from 2017 but still i just faced the same problem and ended up here.我知道这篇文章是 2017 年的,但我仍然遇到了同样的问题并最终到了这里。 And as it looks like you never found your mistake I'll write it here for anyone else that founds this post.看起来你从未发现你的错误,我会写在这里给其他发现这篇文章的人。

The problem is that when you call:问题是当你打电话时:

CreatedAtRoute("GetDocument", new { version = "1", controller = "Document", guid = doc.Guid.ToString("N")}, document);

You are telling the program to look for a "GetDocument" function that receives 3 parameters, in this case 3 strings but your actual "GetDocument" definition receives only 1 string that is your "guid":您告诉程序查找接收 3 个参数的“GetDocument”函数,在本例中为 3 个字符串,但您的实际“GetDocument”定义仅接收 1 个字符串,即您的“guid”:

[HttpGet("{guid}", Name = "GetDocument")]
public IActionResult GetByGuid(string guid)
{
    var doc = DocumentDataProvider.Find(guid);
    if (doc == null)
        return NotFound();

    return new ObjectResult(doc) {StatusCode = 200};
}

So for it to work you should have it like this:所以为了让它工作,你应该像这样:

CreatedAtRoute("GetDocument", new { guid = doc.Guid.ToString("N")}, document);

Another option would be to create a new get method with 3 strings and maybe you'll have to call it something different than "GetDocument".另一种选择是使用 3 个字符串创建一个新的 get 方法,也许您必须将其命名为与“GetDocument”不同的名称。

Hope this helps the next one that comes looking for this :D希望这有助于下一个寻找这个的人:D

ASP.net core 3 ASP.net 核心 3

Why this problem occurs:为什么会出现这个问题:

"As part of addressing dotnet/aspnetcore#4849 , ASP.NET Core MVC trims the suffix Async from action names by default . Starting with ASP.NET Core 3.0, this change affects both routing and link generation." “作为解决dotnet/aspnetcore#4849问题的一部分, ASP.NET Core MVC trims the suffix Async from action names by default删除trims the suffix Async from action names by default 。从 ASP.NET Core 3.0 开始,此更改会影响路由和链接生成。”

See more: https://docs.microsoft.com/en-us/dotnet/core/compatibility/aspnetcore#mvc-async-suffix-trimmed-from-controller-action-names查看更多: https : //docs.microsoft.com/en-us/dotnet/core/compatibility/aspnetcore#mvc-async-suffix-trimmed-from-controller-action-names

As @Chris Martinez says in this thread :正如@Chris Martinez 在 此线程中所说:

The reason for the change was not arbitrary;更改的原因并非随意; it addresses a different bug.它解决了一个不同的错误。 If you're not affected by said bug and want to continue using the Async suffix as you had been doing.如果您不受上述错误的影响,并且想继续像以前一样使用 Async 后缀。

How to solve怎么解决

Re-enable it:重新启用它:

services.AddMvc(options =>
{
   options.SuppressAsyncSuffixInActionNames = false;
});

You should now pass the createActionName parameter including the Async suffix like this:您现在应该传递包含Async后缀的createActionName参数,如下所示:

return CreatedAtAction("PostAsync", dto)

I'll answer my own question: It was really a bug in the versioning package of microsoft and it's gonna be fixed soon.我会回答我自己的问题:这确实是微软版本控制包中的一个错误,很快就会修复。

https://github.com/Microsoft/aspnet-api-versioning/issues/18https://github.com/Microsoft/aspnet-api-versioning/issues/18

I just used return CreatedAtAction("ActionMethodName", dto);我只是使用 return CreatedAtAction("ActionMethodName", dto); instead until they fix that bug.相反,直到他们修复该错误。

Another reason this error occurs is b/c when you use the CreatedAtAction to return 201 , ASP.NET will add a Location header to the response with the url where the resource can be accessed.发生此错误的另一个原因是 b/c,当您使用CreatedAtAction返回201 ,ASP.NET 将向响应添加一个Location标头,其中包含可以访问资源的 url。 It uses the actionName to do this, so the method name needs to match a valid method on your controller.它使用actionName来执行此操作,因此方法名称需要与控制器上的有效方法匹配。 For example:例如:

return CreatedAtAction("GetUser", new { id = user.UserId }, user);

If GetUser does not exist, the call will fail.如果GetUser不存在,调用将失败。 Better practice probably to use:更好的做法可能是使用:

return CreatedAtAction(nameof(GetUser), new { id = user.UserId }, user);

dev guide apidocs 开发指南apidocs

I had the same symptoms but the cause was something else.我有同样的症状,但原因是别的。 Basically it doesn't like the fact that my action method ends with Async .基本上它不喜欢我的操作方法以Async结尾的事实。 It works when I either rename the action method from GetAsync to Get , or add [ActionName("GetAsync")] to the action.当我将操作方法​​从GetAsync重命名为Get或将[ActionName("GetAsync")]添加到操作时,它会起作用。

Source: https://github.com/microsoft/aspnet-api-versioning/issues/601来源: https : //github.com/microsoft/aspnet-api-versioning/issues/601

Just in case, if you are like me, don't like to inherit from any of the in built ControllerX base classes, then you might face this issue, if you use following statement以防万一,如果你像我一样,不喜欢继承任何内置的 ControllerX 基类,那么你可能会遇到这个问题,如果你使用以下语句

  new CreatedAtActionResult(nameof(GetBookOf),
            nameof(BooksController),
            new {id = book.Id.ToString("N")},
            book)

It's because second parameter in the above statement, expect us to pass the constructor name without Controller suffix.这是因为上面语句中的第二个参数,期望我们传递没有Controller后缀的构造函数名称。

Hence, if you change like following, then it would work just fine.因此,如果你像下面这样改变,那么它会工作得很好。

  new CreatedAtActionResult(nameof(GetBookOf),
            "Books",
            new {id = book.Id.ToString("N")},
            book)

This worked for me... https://www.josephguadagno.net/2020/07/01/no-route-matches-the-supplied-values这对我有用...... https://www.josephguadagno.net/2020/07/01/no-route-matches-the-supplied-values

my get-async was...我的异步是...

[HttpGet("{id}", Name = nameof(GetSCxItemAsync))]                            
public async Task<ActionResult<SCxItem>> GetSCxItemAsync(Guid id)

but in order to get around route error I had to add the following before the function declaration...但是为了解决路由错误,我必须在函数声明之前添加以下内容...

[ActionName(nameof(GetSCxItemAsync))]

Instead of this:取而代之的是:

CreatedAtRoute("GetDocument", new { version = "1", controller = "Document", guid = doc.Guid.ToString("N")}, document);

Change your return to the following:将您的退货更改为以下内容:

return CreatedAtRoute("GetDocument",doc, null);

I'm going to stick this in here for some other poor unfortunate soul as I've spent far too long working out what I was doing wrong.我将把这个贴在这里给其他一些可怜的不幸的灵魂,因为我花了太长时间弄清楚我做错了什么。

This is wrong:这是错误的:

app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());

What this does is mask the problem by returning the default route which is [controller] , when what you want it to return is [controller]\\{newly generated id} .这样做是通过返回默认路由[controller]来掩盖问题,当您希望它返回的是[controller]\\{newly generated id}

This is correct:这是对的:

return CreatedAtAction(nameof(GetUser), new { id = user.UserId }, user);

However there is an edge case where this fails, this being when user.UserId is null .但是有一个边缘情况会失败,这是当user.UserIdnull I think that this fails because the id parameter is required, so cannot be null , thus the route doesn't bind.我认为这会失败,因为需要id参数,所以不能为null ,因此路由没有绑定。 It's good that it fails because if it didn't then you would be creating a junk route, but the error message is more cryptic than perhaps it could be.它失败是件好事,因为如果没有,那么您将创建一个垃圾路由,但错误消息可能比它可能更神秘。

In my case I was returning the Id on the input object, which was null, not the newly generated Id on the output object.在我的例子中,我返回的是输入对象上的 Id,它是空的,而不是输出对象上新生成的 Id。

In my case it was a copy/paste error.在我的情况下,这是一个复制/粘贴错误。 The CreatedAtAction method had the wrong action name parameter. CreatedAtAction方法具有错误的操作名称参数。 Make sure the first parameter (the actionName parameter) matches the action name (the function name).确保第一个参数( actionName参数)与操作名称(函数名称)匹配。 The corrected code is seen below:更正后的代码如下所示:

在此处输入图片说明

you must give a name for a method like below and return您必须为如下方法命名并返回

    [HttpGet("{id}",Name = "MethodName")]
    public async Task<IActionResult> MethodName(int id)
    {
        var baseItem = await _baseItemService.BaseItemByIdAsync(baseItemId);
        return Ok(baseItem);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core CreatedAtRoute没有路由匹配提供的值 - ASP.NET Core CreatedAtRoute No route matches the supplied values CreateAtAction在ASP.Net Web API中返回“无路由匹配提供的值” - CreateAtAction returns “No route matches the supplied values” in ASP.Net Web API 当操作名称以“Async”结尾时,Asp.Net Core 3.0 CreatedAtAction 返回“没有路由与提供的值匹配” - Asp.Net Core 3.0 CreatedAtAction returns "no route matches the supplied values" when Action name ends with "Async" ASP.NET Core 2.1 路由 - CreatedAtRoute - 没有路由与提供的值匹配 - ASP.NET Core 2.1 Routing - CreatedAtRoute - No route matches the supplied values API ASP.NET 5“POST”成功,但出现错误“没有路由与提供的值匹配” - API ASP.NET 5 "POST" successfully, although with the error "No route matches the supplied values" ASP.NET Core Web API:通过查询参数路由 - ASP.NET Core Web API : route by query parameter 将中间件附加到 ASP.NET Core Web API 中的特定路由? - Attaching middleware to a specific route in ASP.NET Core Web API? ASP.NET 内核 Web API 自定义路由不起作用 - ASP.NET Core Web API custom route not working 没有路由与提供的值匹配 - No route matches the supplied values ASP.NET Web API 2 中的路由别名 - Route Aliases in ASP.NET Web API 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM