Как перехватить GET-запрос в api перед выполнением в ASP.NET? - PullRequest
0 голосов
/ 25 апреля 2019

Я пытаюсь выяснить, как перехватить вызов GET перед выполнением в .NET Framework.

Я создал 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 голосов
/ 25 апреля 2019

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
    }
}
...