如何从Web请求的URL中确定对象绑定的值?
本文关键字:对象 绑定 URL Web 请求 | 更新日期: 2023-09-27 18:12:56
大致如下:
<<p> Api控制器/strong>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;
});
I tried:
var request = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
var queryPairs = request.GetQueryNameValuePairs();
通过queryPairs,但是在运行时HttpContext.Current
是null
。
任何想法-我如何从url中获得值并在我的Ninject模块中访问?
提前感谢!
我希望这是我想要的功能。似乎有效。(当然它很丑。)
我创建了一个带有静态属性的类:
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;