如何在actionContext中从URL获取参数.. NET Web API 2



如果我有一个这样的路由:

api/account/{id}/devices

如何在动作过滤器中从actionContext获得id值?

当路由为api/account/{id}时,我使用

actionContext.Request.RequestUri.Segments.Last()

是否有一个可靠的方法来获得任何参数从url字符串,如果我知道参数名称,但不是在哪里它驻留在url?

(ActionContext.ActionArguments均为null, btw).

@orsvon把我推到了一个正确的方向:
什么是Routedata.Values["]?
在web api中没有ViewBag,但这个想法是正确的。
如果你有一些过滤器或属性,你需要得到一些参数,你可以这样做:

public class ContractConnectionFilter : System.Web.Http.AuthorizeAttribute
{
private string ParameterName { get; set; }
public ContractConnectionFilter(string parameterName)
{
ParameterName = parameterName;
}

private object GetParameter(HttpActionContext actionContext) 
{
try
{
return actionContext.RequestContext.RouteData.Values
//So you could use different case for parameter in method and when searching
.Where(kvp => kvp.Key.Equals(ParameterName, StringComparison.OrdinalIgnoreCase))
.SingleOrDefault()
//Don't forget the value, Values is a dictionary
.Value;
}
catch
{
return null;
}
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
object parameter = GetParameter(actionContext);
... do smth...
}
}

,并像这样使用:

[HttpGet, Route("account/{id}/devices/{name}")]
[ContractConnectionFilter(parameterName: "ID")] //stringComparison.IgnereCase will help with that
//Or you can omit parameterName at all, since it's a required parameter
//[ContractConnectionFilter("ID")]
public HttpResponseMessage GetDevices(Guid id, string name) {
... your action...
}

最新更新