首页 > 解决方案 > FromUrl 模型的自定义属性名称

问题描述

我有一个用于绑定 QueryString 的模型,它遵循 c# 的命名对话,但 QueryString 处于不同的命名对话中。如何为分配给 vis 的模型属性提供自定义属性名称FromUrl

// Will NOT work
public class FormatDatabaseRequest
{
    [JsonProperty("_type")]
    public string Type { get; set; }

    [JsonProperty(Name = "awef_flag")]
    public string AwefFlag { get; set; }
}

// Controller.cs
[HttpPost]
public async Task<HttpResponseMessage> FormatDatabaseAsync([FromUri] FormatDatabaseRequest request) {}

// Sample URL (QueryString MUST be named _type and awef_flag)
// https://localhost:43521/myControllerName?_type=asdfa&awef_flag=asdf

标签: c#asp.netasp.net-web-api

解决方案


如果你想像这样从 URL 中获取字段,我建议使用[FromQuery]属性,如下所示:

public async Task<HttpResponseMessage> Get([FromQuery] FormatDatabaseRequest data)

那么,这样的网址

https://localhost:43521/myControllerName?type=asdfa&awefflag=asdf

将被正确解析为您的对象:)


推荐阅读