1. 程式人生 > 其它 >.NET Core 獲取url中請求引數值(QueryString)

.NET Core 獲取url中請求引數值(QueryString)

1、通過方法引數獲取

可以[FromQuery]用來將特定模型繫結到引數:

[HttpGet]
public IActionResult Get([FromQuery(Name = "appid")] string appid)
{
        Session result = DispatchHelper.GetSession(appid);
        if (result != null)
             return new JsonResult(new { openid = result.openid, session_key = result.session_key, unionid = result.unionid });
         
return new NoContentResult(); }

2、通過HttpContext.Request.Query獲取

[HttpGet]
public IActionResult GetPage()
{
        string appid = HttpContext.Request.Query["appid"].ToString();
        Session result = DispatchHelper.GetSession(appid);
        if (result != null)
             return new JsonResult(new
{ openid = result.openid, session_key = result.session_key, unionid = result.unionid }); return new NoContentResult(); }

3、通過model獲取

通過model中指定[FromQuery]引數的屬性來獲取Url中的引數。

[HttpGet]
public IActionResult GetPage(ApiModel model)
{
    Session result = DispatchHelper.GetSession(model);
        
if (result != null) return new JsonResult(new { openid = result.openid, session_key = result.session_key, unionid = result.unionid }); return new NoContentResult(); }
public class ApiModel
{
    [FromRoute]
    public int Id { get; set; }
    [FromQuery]
    public string Url { get; set; }
    [FromQuery]
    public int? PageId { get; set; }
}