2014-10-27 15 views
1

我在構建一個很酷的自定義HttpClient包裝器,它將使用屬性來構建動態路由等。我在解決問題時遇到了一個問題從該方法的屬性訪問方法參數值。以下是我的自定義屬性的方法示例:如何從.NET中的屬性類讀取方法參數信息(名稱和值)

[RestEndpoint("appointment/{appointmentId}")] 
public AppointmentDto GetAppointmentById(int appointmentId) 
{ 
    //code calls base class methods to hit the endpoint defined in this method's attribute 
} 

以下是我的屬性類。在我的屬性類中,我想讀取它所連接的方法的參數,並在GetDynamicEndpoint()方法中構建Uri,並執行一些替換和正則表達式。

我似乎無法弄清楚如何實際獲取給定屬性所附屬的方法信息。我可以做相反的事情(從方法中讀取屬性信息)。

[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] 
public sealed class RestEndpoint : Attribute 
{ 
    public HttpVerb Verb { get; set; } 

    public string Uri { get; set; } 

    public RestEndpoint(string uri) 
    { 
     Verb = HttpVerb.Get; 
     Uri = uri; 
    } 

    public RestEndpoint(HttpVerb verb, string uri) 
    { 
     Verb = verb; 
     Uri = uri; 
    } 

    public string GetDynamicEndpoint() 
    { 
     //get method for this attribute and read it's parameters 
     //in order to build dynamic endpoint based on method's parameter values   

     return "dynamic endpoint"; 
    } 

} 
+0

你在找什麼樣的以下內容:http://stackoverflow.com/questions/2798516/asp-mvc-c-is-it-possible-to-pass-dynamic-values-into-an-attribute – MethodMan 2014-10-27 19:23:50

+1

什麼你的意思是「獲取該屬性的方法並閱讀它的參數」?具有方法的屬性具有多對多的關係,並且考慮到它們表示代碼單元的靜態不可更改屬性,它們與它們所應用的方法(類)完全斷開連接。但是,如果我理解你是正確的,你可以得到該方法的屬性實例,並使用它的例程與適當的參數:'公共字符串GetDynamicEndpoint(IData數據)'。 – 2014-10-27 19:30:39

+0

@DJKRAZE是的,但顯然我沒有過濾器上下文或控制器值提供程序的奢侈。 – Britton 2014-10-27 19:31:05

回答

1

所以從評論和研究來看,我在這裏嘗試做的事情對於當前內置的.Net框架功能是不可能的。但是,我確實接受了@尤金的建議,並將參數從方法傳遞給屬性以構建動態路由。截至向上是這樣的:

[UseRestEndpoint("appointment/{first}/{last}")] 
public AppointmentDto GetAppointmentById(string first, string last) 
{ 
    return Send<AppointmentDto>(new { first, last }); 
} 

和屬性呼叫建立與動態路由URI的動態傳遞的對象:

public string GetDynamicEndpoint(dynamic parameters) 
{ 
    if (!Uri.Contains("{") && !Uri.Contains("}")) 
     return Uri; 

    var valueDictionary = GetUriParameterValueDictionary(parameters); 

    string newUri = Uri; 
    foreach (KeyValuePair<string, string> pair in valueDictionary) 
     newUri = newUri.Replace(string.Format("{{{0}}}", pair.Key), pair.Value); 

    return newUri; 
} 

private Dictionary<string, string> GetUriParameterValueDictionary(object parameters) 
{ 
    var propBag = parameters.ToPropertyDictionary(); 
    return GetUriParameters().ToDictionary(s => s, s => propBag[s]); 
} 


private IEnumerable<string> GetUriParameters() 
{ 
    Regex regex = new Regex(@"(?<={)\w*(?=})"); 
    var matchCollection = regex.Matches(Uri); 

    return (from Match m in matchCollection select m.Value).ToList(); 
} 

這是不是所有的這個工作實現代碼,但結果卻讓這個概念發揮了作用。多謝大家的評價。

相關問題