Asp.net web api DelegatingHandler请求来源

Asp.net web api DelegatingHandler请求来源,asp.net-web-api,Asp.net Web Api,我有一个DelegatingHandler来验证请求标头中包含的ApiKey: public class ApiKeyHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (!ApiKey.Verif

我有一个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属性,但这对我不起作用。

我现在使用IP地址:
dynamicrequest.Properties[MS_HttpContext].Request.UserHostAddress

因为您似乎需要调用者的IP,所以有一个很好的扩展方法,可以在自主机和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;
    }
}

这是解决我问题的办法。所以它应该是正确的。