如何在ASP.NET中执行前拦截api中的GET请求?
How to intercept GET request in api before execution in ASP.NET?
我正在尝试弄清楚如何在 .NET Framework 中执行之前拦截 GET 调用。
我创建了 2 个应用程序:一个 front-end(调用 API 并用它发送自定义 HTTP headers)和一个 back-end API :
Front-end 方法调用 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);
}
}
Back-end 收到请求:
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 请求时,我添加了自定义 headers,我正在寻找一种在执行发生之前从传入的 GET 中提取这些内容的方法。
希望有人能帮忙!
提前致谢
ActionFilterAttribute
,如以下示例所示,我创建了属性并将其放在 api 基础 class 上,其中所有 api class es inherit from,在到达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
}
}
我正在尝试弄清楚如何在 .NET Framework 中执行之前拦截 GET 调用。
我创建了 2 个应用程序:一个 front-end(调用 API 并用它发送自定义 HTTP headers)和一个 back-end API :
Front-end 方法调用 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);
}
}
Back-end 收到请求:
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 请求时,我添加了自定义 headers,我正在寻找一种在执行发生之前从传入的 GET 中提取这些内容的方法。
希望有人能帮忙!
提前致谢
ActionFilterAttribute
,如以下示例所示,我创建了属性并将其放在 api 基础 class 上,其中所有 api class es inherit from,在到达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
}
}