How to filter local requests in asp.net web api?

2019-07-10 06:08发布

I'm having a situation that is getting kind of annoying with asp.net web api. The thing is i have an API which is already in production, however I'm constantly making changing and deploying again.

I have a filter, which takes care of checking if the request is https, that works awesome on production, but when requests are local the filter blocks all http requests, which is not what I want. I would like to allow local requests with http. I have a filter which does the exact same thing on MVC3, and I can do something like:

filterContext.HttpContext.Request.IsLocal

Is there any work around to this problem?

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-10 06:31

You can directly use the IsLocal extension method of the HttpRequestMessage. link

For example:

using System.Net.Http;

...

public void PostUser(User user) 
{
    if (!base.Request.IsLocal())    
    { 
        ...
查看更多
爷、活的狠高调
3楼-- · 2019-07-10 06:31

MS_Islocal property was not available to me instead this worked -

if (Request != null && Request.Properties.ContainsKey("MS_RequestContext")){
                    var context = Request.Properties["MS_RequestContext"] as HttpRequestContext;
                    return context.IsLocal;
                }
                return false;
查看更多
相关推荐>>
4楼-- · 2019-07-10 06:39

if you are using webhost i.e hosting webapi in asp.net, you can access the HttpContext using

HttpContextBase httpContextBase;
request.Properties.TryGetValue("MS_HttpContext", out httpContextBase);

You can then use httpContextBase.Request.IsLocal to determine if the request is local.

查看更多
爷、活的狠高调
5楼-- · 2019-07-10 06:42

You can use an extension method to access the value within the Request.Properties Dictionary. For example:

public static class HttpRequestExtensions
{
   public static bool IsLocal(this HttpRequestMessage request)
   {
       var flag = request.Properties["MS_IsLocal"] as Lazy<bool>;
       return flag != null && flag.Value;
   }
}

This has the added benefit of also working when self-hosting.

查看更多
登录 后发表回答