Nik*_*dze 4 c# windows-services ip-address asp.net-web-api owin
我需要一个非常简单的事情 - 在Web API控制器中获取远程主机IP地址.本文将介绍如何在您进行虚拟主机或自托管时执行此操作.不幸的是,所描述的解决方案不适用于使用Owin自托管的Web API(好吧,我无法使其工作:)).我使用Windows服务来托管Web API.
所以,问题是:如何在使用Owin的Windows服务中自托管的Web API控制器中获取远程主机IP地址?
我需要远程IP地址的控制器:
internal class ItemController : ApiController
{
[HttpPost]
public HttpResponseMessage AddItem([FromBody] string data)
{
// Need to get remote host IP address here
return Request.CreateResponse(HttpStatusCode.OK);
}
}
Run Code Online (Sandbox Code Playgroud)
启动配置Web API的类:
internal class StartUp
{
public void Configuration(IAppBuilder appBuilder)
{
var httpConfig = new HttpConfiguration();
httpConfig.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(httpConfig);
}
}
Run Code Online (Sandbox Code Playgroud)
我使用Windows服务来托管Web API.以下是服务的OnStart方法:
protected override void OnStart(string[] args)
{
var baseAddress = "http://localhost:5550/";
// Start OWIN
WebApp.Start<StartUp>( url: baseAddress );
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Kir*_*lla 11
您应该可以通过执行以下操作来获取它:
OwinContext owinContext = (OwinContext)webapiHttpRequestMessage.Properties["MS_OwinContext"];
string ipaddress = owinContext.Request.RemoteIpAddress;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6882 次 |
| 最近记录: |