首页 > 解决方案 > 接受 .NET CORE 中的 URL 参数

问题描述

我是 .NET CORE 的新手,我想是否可以更改请求 url 的默认格式。让我解释。我在控制器上有两个 get 方法,用于获取列表并获取 1 个元素的信息

[Route("api/[controller]/")]
[ApiController]
public class Department : ControllerBase
{
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    [HttpGet("{id:int}")]
    public string GetDepartamento(int id)
    {
        return "value";
    }

    [HttpPost]
    public void Post([FromBody] string value)
    {
    }
  }
}

为了调用这些资源你使用

https://localhost:44309/api/department
https://localhost:44309/api/department/1

但我不仅需要为这个控制器使用这种格式,还需要为所有控制器使用这种格式

GET:https://localhost:44309/api/department
GET:https://localhost:44309/api/department?id=1
POST:https://localhost:44309/api/department (data on the body of http call)
PUT:https://localhost:44309/api/department?id=1 (data on the body of http call)
DELETE:https://localhost:44309/api/department?id=1

我正在处理一个新项目(.net core web application MVC),所以启动和程序文件没有被修改。

标签: .netasp.net-core-mvc

解决方案


我在控制器上有两个 get 方法,用于获取列表并获取 1 个元素的信息

我需要使用这种格式

GET:https://localhost:44309/api/department

GET:https://localhost:44309/api/department?id=1

如果您想根据查询字符串将请求与预期的操作相匹配,您可以尝试实现自定义ActionMethodSelectorAttribute并将其应用于您的操作,如下所示。

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class CheckQueryStingAttribute : ActionMethodSelectorAttribute
{
    public string QueryStingName { get; set; }
    public bool CanPass { get; set; }
    public CheckQueryStingAttribute(string qname, bool canpass)
    {
        QueryStingName = qname;
        CanPass = canpass;
    }

    public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
    {
        StringValues value;

        routeContext.HttpContext.Request.Query.TryGetValue(QueryStingName, out value);

        if (QueryStingName == "" && CanPass)
        {
            return true;
        }
        else
        {
            if (CanPass)
            {
                return !StringValues.IsNullOrEmpty(value);
            }

            return StringValues.IsNullOrEmpty(value);
        }
    }
}

将其应用于操作

[HttpGet]
[CheckQuerySting("id", false)]
[CheckQuerySting("", true)]
public IEnumerable<string> Get()
{
    return new string[] { "value1", "value2" };
}

[HttpGet]
[CheckQuerySting("id", true)]
[CheckQuerySting("", false)]
public string GetDepartamento(int id)
{
    return "value";
}

测试结果

在此处输入图像描述


推荐阅读