DelegatingHandler请求来源

时间:2014-08-25 08:02:13

标签: asp.net-web-api

我有一个DelegatingHandler来验证请求标头中包含的ApiKey:

public class ApiKeyHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (!ApiKey.VerifyRequest(request))
        {
            var response = request.CreateErrorResponse(HttpStatusCode.Forbidden, "Invalid Api Key");
            var tsc = new TaskCompletionSource<HttpResponseMessage>();
            tsc.SetResult(response);
            return tsc.Task;
        }

        return base.SendAsync(request, cancellationToken);
    }
}

现在我想扩展它以检查请求的来源,因为只有外部请求才需要此APIKey(还不需要CORS)。 外部由域及其独有的服务器到服务器定义。

我找到了Is_Local属性,但这对我不起作用。

2 个答案:

答案 0 :(得分:0)

我现在要使用IP地址: ((dynamic)request.Properties["MS_HttpContext"]).Request.UserHostAddress;

答案 1 :(得分:0)

由于您似乎需要调用者的IP,WebApiContrib有一个适用于自托管主机和Web主机的良好扩展方法:

public static class HttpRequestMessageExtensions
{
    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

    public static string GetClientIpAddress(this HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey(HttpContext))
        {
            dynamic ctx = request.Properties[HttpContext];
            if (ctx != null)
            {
                return ctx.Request.UserHostAddress;
            }
        }

        if (request.Properties.ContainsKey(RemoteEndpointMessage))
        {
            dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
            if (remoteEndpoint != null)
            {
                return remoteEndpoint.Address;
            }
        }

        return null;
    }
}