我刚刚在我的WebAPI项目上更新(从v3.x)到最新版本的AttributeRouting,它刚刚开始产生我以前从未见过的错误.
现在无论何时调用API,我都会收到如下错误:
System.InvalidOperationException: The constraint entry 'inboundHttpMethod' on the route with route template 'my/path' must have a string value or be of a type which implements 'IHttpRouteConstraint'.
at System.Web.Http.Routing.HttpRoute.ProcessConstraint(HttpRequestMessage request, Object constraint, String parameterName, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)
at System.Web.Http.Routing.HttpRoute.ProcessConstraints(HttpRequestMessage request, HttpRouteValueDictionary values, HttpRouteDirection routeDirection)
at System.Web.Http.Routing.HttpRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request)
at AttributeRouting.Web.Http.Framework.HttpAttributeRoute.GetRouteData(String virtualPathRoot, HttpRequestMessage request)
at System.Web.Http.WebHost.Routing.HttpWebRoute.GetRouteData(HttpContextBase httpContext)
at System.Web.Routing.RouteCollection.GetRouteData(HttpContextBase httpContext)
at System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context)
at System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Run Code Online (Sandbox Code Playgroud)
几个月来它一直没有问题.
非文档详细信息有任何用法更改.我的配置文件看起来正确.
出了什么问题?我找不到其他人举报此事.
我有一个涉及多个领域的MVC5项目。我有一个默认区域(名为Default),其中有一个默认控制器(名为DefaultController)。这可以在站点路线上访问。
[RouteArea]
public class DefaultController : Controller
{
[Route]
public ActionResult Index()
{
return View("Index");
}
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyProject.Areas.Default.Controllers" }
);
}
Run Code Online (Sandbox Code Playgroud)
控制器已正确加载,但是Areas/Default/Views/Default/Index.cshtml找不到视图(位于)。为什么MVC找不到正确的位置?
The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc asp.net-mvc-routing attributerouting asp.net-mvc-5
根据我的设计要求,我想从控制器中排除后缀'Controller'并将其替换为'Resource'.因此'FundsController'将成为'FundsResource'.
问题是当我更改替换术语'Controller'时,我无法通过基于约定或属性路由的路由到我的指定操作,并且得到一个错误,指出找不到具有此名称的控制器.
如何满足上述设计要求,并且能够无问题地路由?在基于约定或属性路由?或者,我们是否可以合并基于约定和属性路由的好处来实现这一目标?
提前致谢.
asp.net-mvc-routing asp.net-web-api attributerouting asp.net-mvc-5 asp.net-web-api2
在ASP.Net MVC 5中使用属性路由时,您将调用命令routes.MapMvcAttributeRoutes();,然后将Route()标签添加到要为其构建路由的Controller / Action中。我现在正尝试在ASP.Net MVC 6中执行此操作,并且发现了许多页面向您展示了如何执行此操作,这与MVC 5中的操作确实没有什么不同,但是它们没有向您显示在哪里或如何注册这些路由。
ASP.Net MVC 6是否只是为您自动提供它,还是有一个等同于routes.MapMvcAttributeRoutes();我必须在哪里调用的功能?
我有一个API动作:
[HttpGet, Route("{id}/overview/")]
public async Task<HttpResponseMessage> Overview(string id, DateTime from, DateTime? to)
{
...
}
Run Code Online (Sandbox Code Playgroud)
正如您所注意到的,to是可选参数,但是当我发出请求时:
"/api/cream/3d7dd454c00b/overview?from=2016-09-04T18:00:00.000Z
我收到404错误.如果我to从参数中删除:
public async Task<HttpResponseMessage> Overview(string id, DateTime from)
一切正常.如何强制它与to参数一起工作?
这是我的控制器的外观:
[Route("api/[controller]")]
[Produces("application/json")]
public class ClientsController : Controller
{
private readonly IDataService _clients;
public ClientsController(IDataService dataService)
{
_clients = dataService;
}
[HttpPost]
public int Post([Bind("GivenName,FamilyName,GenderId,DateOfBirth,Id")] Client model)
{
// NB Implement.
return 0;
}
[HttpGet("api/Client/Get")]
[Produces(typeof(IEnumerable<Client>))]
public async Task<IActionResult> Get()
{
var clients = await _clients.ReadAsync();
return Ok(clients);
}
[HttpGet("api/Client/Get/{id:int}")]
[Produces(typeof(Client))]
public async Task<IActionResult> Get(int id)
{
var client = await _clients.ReadAsync(id);
if (client == null)
{
return NotFound();
}
return Ok(client);
}
[HttpGet("api/Client/Put")]
public void Put(int id, [FromBody]string value) …Run Code Online (Sandbox Code Playgroud) asp.net-mvc attributerouting dotnet-httpclient asp.net-core-mvc
我有一个Web API,看起来像以下......
public class LeaguesController : ApiController
{
//api/Leagues/active/1
//api/Leagues/complete/1
//api/Leagues/both/1
[GET("api/Leagues/{type}/{id}")]
public List<Competition> Get([FromUri]int id,
[FromUri]CompetitionManager.MiniLeagueType type)
{
return CompetitionManager.GetUsersMiniLeagues(id, true, type);
}
//api/Leagues/GetMiniLeagueTable/3
[GET("api/Leagues/GetMiniLeagueTable/{id}")]
public List<SportTableRow> GetMiniLeagueTable([FromUri]int id)
{
return SportManager.GetMiniLeagueTable("", id).TableRows;
}
}
Run Code Online (Sandbox Code Playgroud)
当我调用第一种方法时Get,这很好用.当我使用fiddler或Chrome REST Client调用第二种方法时GetMiniLeagueTable,我收到以下错误:
{消息:"请求无效." MessageDetail:"参数字典包含参数'type'的非可为空类型'CompetitionManager + MiniLeagueType'的空条目,方法'System.Collections.Generic.List`1 [竞争] Get(Int32,MiniLeagueType)''LeaguesController '.可选参数必须是引用类型,可以为空的类型,或者声明为可选参数." }
我AttributeRouting用来装饰方法,但这似乎不起作用.在我介绍之前它工作正常MiniLeagueType.
有人遇到过这个问题,还是你能指出我哪里出错了?
我正在创建一个WebApi2服务,我想要实现的一个方法表示来自内部树结构中的对象的HTTP GET - 所以请求将是:
GET /values/path/path/to/object/in/tree
Run Code Online (Sandbox Code Playgroud)
所以我希望我的方法接收"path/to/object/in/tree".
但是,当我运行它时,我只得到404,而且有趣的是我得到的404与标准的IIS 404不同.它的标题是'/'应用程序中的'服务器错误',而完全无效的那个资源标题为'HTTP错误404.0 - 未找到'.
我正在玩默认模板试试看我是否可以使用它,因此相似性.
我有这个 RouteConfig
public static void RegisterRoutes(RouteCollection routes)
{
var route = routes.MapRoute(
name: "CatchAllRoute",
url: "values/path/{*pathValue}",
defaults: new { controller = "Values", action = "GetPath" });
}
Run Code Online (Sandbox Code Playgroud)
这是我的ValuesController:
[System.Web.Mvc.AuthorizeAttribute]
[RoutePrefix("values")]
public class ValuesController : ApiController
{
[Route("test/{value}")]
[HttpGet]
public string Test(string value)
{
return value;
}
[HttpGet]
public string GetPath(string pathValue)
{
return pathValue;
}
}
Run Code Online (Sandbox Code Playgroud)
有趣的是,如果我派生Controller而不是ApiController它工作正常,但那么正常的属性路由不起作用.
我尝试按照这篇文章(http://www.tugberkugurlu.com/archive/asp-net-web-api-catch-all-route-parameter-binding)中的方法进行操作,但我无法使用它.
我敢肯定我错过了一些愚蠢的事情,但是花了几个小时才开始,我觉得谨慎地问我做错了什么.
谢谢 …
我在控制器级别应用了一个路由属性,但是我希望将一个动作排除在路由之外.没有覆盖,但完全排除了路线.怎么能实现这一目标?
比方说我有:
[RoutePrefix("promotions")]
[Route("{action=index}")]
public class ReviewsController : Controller
{
// eg.: /promotions
public ActionResult Index() { ... }
// eg.: /promotions/archive
public ActionResult Archive() { ... }
// eg.: /promotions/new
public ActionResult New() { ... }
// eg.: /promotions/edit/5
[Route("edit/{promoId:int}")]
public ActionResult Edit(int promoId) { ... }
public void Internal() { ... }
}
Run Code Online (Sandbox Code Playgroud)
我希望内部不要被路由.
我原本期望找到[DoNotRoute]或[Ignore]属性,但我没有找到类似的东西.
与此问题类似,但对于新的ASP.NET Core.
我可以覆盖一个动作的路由名称:
[ActionName("Bar")]
public IActionResult Foo() {
Run Code Online (Sandbox Code Playgroud)
我可以使用属性路由为控制器执行此操作吗?
[?("HelloController")]
public SomeController : Controller {
Run Code Online (Sandbox Code Playgroud)
它应该允许使用标记助手生成链接:
<a asp-controller="some" ... // before
<a asp-controller="hello" ... // after
Run Code Online (Sandbox Code Playgroud) 我创建了一个空项目。
启动.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddLocalization(options => options.ResourcesPath = "Resources");
services.AddMvc().AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix).AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("de-DE"),
new CultureInfo("tr-TR"),
};
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
// options.RequestCultureProviders = new List<IRequestCultureProvider> { new CookieRequestCultureProvider() };
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var localizationOption = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(localizationOption.Value);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles(); …Run Code Online (Sandbox Code Playgroud) 我正在使用.NET 4上的Web API(nuget上的WebAPI版本4.0.30506)托管REST API.为了允许更精细的属性路由,我还在我的解决方案中包含了attributerouting.net.
我有2个冲突的属性路由.冲突的原因是我们在一次调用中通过字符串标识符查询,并在另一次调用中通过字符串操作+数字标识符进行查询.HTTP响应中抛出的消息读取Multiple actions were found that match the request.以下是演示这两者的示例查询:
1) http://example/api/libraries/?libraryId=some_library (some_library is a string identifier)
2) http://example/api/libraries/bookStatus/1 (1 is the library database ID)
Run Code Online (Sandbox Code Playgroud)
我一直在努力通过不同的方式来完成这项工作.我当前的控制器签名如下所示:
[GET("api/libraries/?libraryId={libraryId}", Precedence = 2)]
[System.Web.Http.HttpGet]
public Library QueryLibraryByLibraryId(string libraryId){}
[GET("api/libraries/bookStatus/{libraryId:long}", Precedence = 1)]
[System.Web.Http.HttpGet]
public Dictionary<string, Dictionary<string, string>> QueryBookStatus(long libraryId){}
Run Code Online (Sandbox Code Playgroud)
我可以看到为什么路由可能会混淆:它如何知道字符串标识符"bookStatus/1"无效是一个很好的问题.但是,我认为这应该更容易定义一些约束.
如何在保持此类签名结构的同时解决这些冲突?