在ASP.NET中执行之前如何在api中拦截GET请求?

时间:2019-04-25 08:15:05

标签: c# asp.net-mvc api handler interceptor

我试图弄清楚如何在.NET框架中执行执行之前拦截GET调用。

我已经创建了2个应用程序:一个前端(调用API并使用它发送自定义HTTP标头)和一个后端API:

调用API的前端方法:

[HttpGet]
    public async Task<ActionResult> getCall()
    {
        string url = "http://localhost:54857/";
        string customerApi = "2";

        using (var client = new HttpClient())
        {
            //get logged in userID
            HttpContext context = System.Web.HttpContext.Current;
            string sessionID = context.Session["userID"].ToString();

            //Create request and add headers
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Custom header
            client.DefaultRequestHeaders.Add("loggedInUser", sessionID);

            //Response
            HttpResponseMessage response = await client.GetAsync(customerApi);
            if (response.IsSuccessStatusCode)
            {
                string jsondata = await response.Content.ReadAsStringAsync();
                return Content(jsondata, "application/json");
            }
            return Json(1, JsonRequestBehavior.AllowGet);
        }
    }

接收请求的后端:

public class RedirectController : ApiController
{
    //Retrieve entire DB
    ConcurrentDBEntities dbProducts = new ConcurrentDBEntities();

    //Get all data by customerID
    [System.Web.Http.AcceptVerbs("GET")]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("{id}")]
    public Customer getById(int id = -1)
    {
        //Headers uitlezen
        /*var re = Request;
        var headers = re.Headers;

        if (headers.Contains("loggedInUser"))
        {
            string token = headers.GetValues("loggedInUser").First();
        }*/

        Customer t = dbProducts.Customers
            .Where(h => h.customerID == id)
            .FirstOrDefault();
        return t;
    }
}

路由:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

上面显示的代码工作正常,我获得了API调用的正确结果,但我正在寻找一种方法来拦截所有传入的GET请求,然后即时返回响应,因此我可以修改此控制器并为其添加逻辑。在发出GET请求时,我添加了自定义标头,我正在寻找一种在执行之前从传入的GET中提取所有标头的方法。

希望有人可以提供帮助!

预先感谢

1 个答案:

答案 0 :(得分:0)

ActionFilterAttribute(在以下示例中使用),我创建了该属性并将其放在所有基类都继承自api的api基类上,在到达api方法之前已输入OnActionExecuting。我们可以在那里检查RequestMethod是否为"GET",然后执行您打算在那里做的任何事情。

public class TestActionFilterAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.Request.Method.Method == "GET")
        {
            //do stuff for all get requests
        }
        base.OnActionExecuting(actionContext);
    }
}

[TestActionFilter] // this will be for EVERY inheriting api controller 
public class BaseApiController : ApiController
{

}

[TestActionFilter] // this will be for EVERY api method
public class PersonController: BaseApiController
{
    [HttpGet]
    [TestActionFilter] // this will be for just this one method
    public HttpResponseMessage GetAll()
    {
        //normal api stuff
    }
}