开发手册 欢迎您!
软件开发者资料库

ASP.NET Core 获取url中请求参数值(QueryString)的方法及示例代码

本文主要介绍ASP.NET Core中,通过QueryString方式获取url中请求参数值的方法,以及相关示例代码。

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