2014-07-14 41 views
1

这里大概是我有:如何确定来自Web请求URL的Ninject绑定的值?

阿比控制器

public class MyController : ApiController 
{ 
    public MyController(IServiceThatNeedsPrinicipal myService) 
    { 
    } 
} 

为MyService

public class MyService: IServiceThatNeedsPrinicipal 
{ 
    public MyService(IMyPrincipal myService) 
    { 
    } 
} 

IMyPrincipal

public interface IMyPrincipal : IPrincipal {} 

这种自我托管网站会得到一个POST要求如:

localhost:9005/Start?UserId=1 

我想要做的是:

this.Bind<IMyPrincipal>().ToMethod(c => 
{ 
    int userId = /* Get UserId from Request -- How do I do this inside a NinjectModule? */ 
    IMyPrincipal mp = CodeToGetMyPrincipalFromUserId(userId); /* I know how to do this */ 
    return mp; 
}); 

我想:

var request = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage; 
var queryPairs = request.GetQueryNameValuePairs(); 

而且通过queryPairs,但在运行时HttpContext.Currentnull

任何想法 - 我如何从网址中获取价值并可在我的Ninject模块中访问?

在此先感谢!

回答

1

我希望这个功能是我想要的。似乎工作。 (这是丑陋的,当然。)

我做了一个类的静态属性:

public class RequestMessage 
{ 
    public static HttpRequestMessage Contents { get; set; } 
} 

然后,我只是增加了一个DelegatingHandler设置它。

public class RequestMessageHandler : DelegatingHandler 
{ 
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     RequestMessage.Contents = request; 
     return base.SendAsync(request, cancellationToken); 
    } 
} 

并将其注册:

config.MessageHandlers.Add(new RequestMessageHandler()); 

而且改变了我的代码使用方法:

var request = RequestMessage.Contents; 
相关问题