我在尝试将过滤器与 Web api 控制器中的所有操作绑定时不断收到此错误。我正在使用 Ninject 3.0 和 ASP.NET MVC 4。
<Response>
<Message>An error has occurred.</Message>
<ExceptionMessage>Sequence contains no elements</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source) at Ninject.Web.WebApi.FilterBindingSyntax.FilterFilterBindingBuilder`1.<>c__DisplayClass15`1.<WithConstructorArgumentFromActionAttribute>b__14(IContext ctx, HttpConfiguration controllerContext, HttpActionDescriptor actionDescriptor) in d:\Projects\Ninject.Web.WebApi\src\Ninject.Web.WebApi\FilterBindingSyntax\FilterFilterBindingBuilder.cs:line 385 at Ninject.Web.WebApi.FilterBindingSyntax.FilterFilterBindingBuilder`1.<>c__DisplayClass12.<WithConstructorArgument>b__11(IContext ctx) in d:\Projects\Ninject.Web.WebApi\src\Ninject.Web.WebApi\FilterBindingSyntax\FilterFilterBindingBuilder.cs:line 363 at Ninject.Parameters.Parameter.<>c__DisplayClass6.<.ctor>b__4(IContext ctx, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Parameters\Parameter.cs:line 60 at Ninject.Parameters.Parameter.GetValue(IContext context, ITarget target) in c:\Projects\Ninject\ninject\src\Ninject\Parameters\Parameter.cs:line 89 at
BaseApiController.cs
[ExceptionHandling, ApiValidation, HttpHeader("X-Robots-Tag", "noindex, nofollow")]
public abstract class BaseApiController : System.Web.Http.ApiController
{
protected readonly IApiAuthenticationService ApiAuthenticationService;
protected BaseApiController(
IApiAuthenticationService apiAuthenticationService)
{
ApiAuthenticationService = apiAuthenticationService;
}
}
全球.asax
kernel.BindHttpFilter<HttpHeaderFilter>(System.Web.Http.Filters.FilterScope.Controller)
.WhenControllerHas<HttpHeaderAttribute>()
.WithConstructorArgumentFromActionAttribute<HttpHeaderAttribute>("name", q => q.Name)
.WithConstructorArgumentFromActionAttribute<HttpHeaderAttribute>("value", q => q.Value);
HttpHeaderFilter.cs
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
namespace Tournaments.Models.Mvc.Filters
{
public class HttpHeaderAttribute : System.Web.Http.Filters.FilterAttribute
{
public string Name { get; set; }
public string Value { get; set; }
public HttpHeaderAttribute(string name, string value)
{
Name = name;
Value = value;
}
}
public class HttpHeaderFilter : System.Web.Http.Filters.IActionFilter
{
private readonly string _name;
private readonly string _value;
public HttpHeaderFilter(string name, string value)
{
_name = name;
_value = value;
}
public bool AllowMultiple
{
get { return false; }
}
public Task<HttpResponseMessage> ExecuteActionFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
{
actionContext.Response.Headers.Add(_name, _value);
return continuation();
}
}
}