【问题标题】:Custom Parameter Names With Special Characters in ASP.NET Web API MVC 4ASP.NET Web API MVC 4 中带有特殊字符的自定义参数名称
【发布时间】:2013-11-25 18:37:33
【问题描述】:

我需要创建一个 Get 方法,该方法在 URL 中采用以下参数名称:

毫秒级 ms-对比度 ms-lang

如您所见,所有名称中都有一个破折号,这在 C# 中是不可能的。如何将我的方法映射到这些参数名称?

public HttpResponseMessage Get(int scale, string contrast string lang)

【问题讨论】:

  • 可以通过自定义模型绑定器来完成。

标签: c# .net asp.net-mvc rest asp.net-web-api


【解决方案1】:

使用FromUriAttribute

public HttpResponseMessage Get([FromUri(Name = "ms-scale")]int scale, [FromUri(Name = "ms-contrast")]string contrast, [FromUri(Name = "ms-lang")]string lang)

【讨论】:

  • 这应该是被接受的答案。无需编写自定义活页夹或其他任何东西 - 只需开箱即用的解决方案。
【解决方案2】:

我之前在其他地方被问过这个问题并找到了这个答案:

Using a dash (-) in ASP.MVC parameters

更新

为了让它与 Web API 一起工作,我们需要对其进行一些修改。

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class BindParameterAttribute : ActionFilterAttribute
{
    public string ViewParameterName { get; set; }
    public string ActionParameterName { get; set; }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var viewParameter = actionContext.Request.RequestUri.ParseQueryString()[ViewParameterName];
        if (!string.IsNullOrWhiteSpace(viewParameter))
            actionContext.ActionArguments[ActionParameterName] = viewParameter;

        base.OnActionExecuting(actionContext);
    }
}

以及如何使用它:

[BindParameter(ActionParameterName = "customData", ViewParameterName = "custom-data")]
public string Get(string customData) {}

请注意,这仅适用于您的数据来自 uri 而不是正文的情况。如何使其与 POST 数据一起使用,我目前还不确定。

【讨论】:

  • 我在方法中设置了一个断点,它似乎没有中断。
  • [ParameterName(ActionParameterName = "scale", ViewParameterName = "ms-scale")] [ParameterName(ActionParameterName = "contrast", ViewParameterName = "ms-contrast")] [ParameterName(ActionParameterName = "语言",ViewParameterName = "ms-lang")] public HttpResponseMessage Get(int scale = 100, string contrast = "standard", string language = "en-us")
  • 对于 Web API,您应该使用 System.Web.Http.Filters 命名空间。你在使用那个命名空间吗?我会试着举个例子。
  • 如果我使用 System.Web.Http.Filters.ActionFilterAttribute ActionExecutingContext 来自哪里?它一直试图引用不正确的 System.Web.Mvc.ActionExecutingContext。
  • 如果参数是 int 似乎不起作用。虽然适用于字符串。
猜你喜欢
  • 1970-01-01
  • 2018-11-22
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多