gpt4 book ai didi

c# - 如何使用 MVC 6 解决 System.InvalidOperationException - 相同的模板

转载 作者:太空狗 更新时间:2023-10-29 18:24:42 27 4
gpt4 key购买 nike

一般来说,我是 ASP.NET 的新手,最近遇到了这个我在网上找不到的错误(可能是因为最近发布的 MVC 6?)

System.InvalidOperationException The following errors occurred with attribute routing information:

错误 1:

Attribute routes with the same name 'GetByIdRoute' must have the same template: Action: 'Appname.Web.Controllers.MemberController.GetById' - Template: 'api/Member/{id:int}' Action: 'Appname.Web.Controllers.PaymentController.GetById' - Template: 'api/Payment/{id:int}' Action: 'Appname.Web.Controllers.PlanController.GetById' - Template: 'api/Plan/{id:int}'

这为 startup.cs 提供了一个代码片段

Line 73:  
Line 74: // Add MVC to the request pipeline.
Line 75: app.UseMvc(routes =>
Line 76: {
Line 77: routes.MapRoute(

突出显示第 75 行

还有这个:

at Microsoft.AspNet.Mvc.ControllerActionDescriptorBuilder.Build(ApplicationModel application) 
at Microsoft.AspNet.Mvc.Core.ControllerActionDescriptorProvider.GetDescriptors()
at Microsoft.AspNet.Mvc.Core.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context)
at Microsoft.AspNet.Mvc.Core.DefaultActionDescriptorsCollectionProvider.GetCollection()
at Microsoft.AspNet.Mvc.Core.DefaultActionDescriptorsCollectionProvider.get_ActionDescriptors()
at Microsoft.AspNet.Mvc.Routing.AttributeRoute.GetInnerRoute()
at Microsoft.AspNet.Mvc.Routing.AttributeRoute..ctor(IRouter target, IActionDescriptorsCollectionProvider actionDescriptorsCollectionProvider, IInlineConstraintResolver constraintResolver, ILoggerFactory loggerFactory)
at Microsoft.AspNet.Mvc.Routing.AttributeRouting.CreateAttributeMegaRoute(IRouter target, IServiceProvider services)
at Microsoft.AspNet.Builder.BuilderExtensions.UseMvc(IApplicationBuilder app, Action<IRouteBuilder> configureRoutes)
at Appname.Web.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) in ... Startup.cs:line 75

最佳答案

您可以指定路由名称。

In Web API, every route has a name. Route names are useful for generating links, so that you can include a link in an HTTP response.

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-names

    [HttpGet("{id}", Name = "GetPerson")]
public IActionResult Get(int id)
{
var item = this.PeopleRepository.GetById(id);

if (item == null)
{
return this.HttpNotFound();
}

return new ObjectResult(item);
}

通过这样做,您可以拥有另一个具有相同操作名称(但不同路由名称)的 Controller

    [HttpGet("{id}", Name = "GetPurchase")]
public IActionResult Get(int id)
{
var item = this.PurchaseRepository.GetById(id);

if (item == null)
{
return this.HttpNotFound();
}

return new ObjectResult(item);
}

关于c# - 如何使用 MVC 6 解决 System.InvalidOperationException - 相同的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30460179/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com