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

Nie*_*den 6 c# api asp.net-mvc 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

接收请求的后端:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

路由:

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 }
        );
    }
Run Code Online (Sandbox Code Playgroud)

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

希望有人可以帮忙!

提前致谢

Sam*_*Sam 6

ActionFilterAttribute,如以下示例所示,我创建了属性并将其放在所有 api 类继承的 api 基类上,OnActionExecuting在到达 api 方法之前输入。我们可以在那里检查是否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
    }
}
Run Code Online (Sandbox Code Playgroud)