2014-04-27 67 views

回答

2

客戶端將不會看到請求屬性,除非您明確地序列化它們。他們完全停留在服務器端。

要回答你的後續問題,這裏有兩種方法可以做到這一點。每個人都沒有「最好」的方式。這一切都取決於您希望信息流動的距離,以及您希望過濾器的通用程度。我個人的偏好是使用控制器對象,但它只是一個偏好。

對於這裏的樣品是簡單值控制器和POCO類:

[MyActionfilter] 
public class ValuesController : ApiController 
{ 
    public string Foo { get; set; } 

    public User Get(User user) 
    { 
     if (Foo != null && user != null) 
     { 
      user.FamilyName = Foo; 
     } 

     return user; 
    } 
} 


public class User 
{ 
    public string FirstName { get; set; } 
    public string FamilyName { get; set; } 
} 

動作濾波器下面天真地執行訪問控制器對象或方法參數。請注意,您可以謹慎應用過濾器或進行類型檢查/字典檢查。

public class MyActionfilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     controller = actionContext.ControllerContext.Controller; 

     // Not safe unless applied only to controllers deriving 
     // from ValuesController 
     ((ValuesController)controller).Foo = "From filter"; 

     // Not safe unless you know the user is on the signature 
     // of the action method. 
     actionContext.ActionArguments["user"] = new User() 
     { 
      FirstName = "From filter" 
     }; 
    } 
} 
+0

有沒有更好的方式來傳遞數據或這是最好的? – Omtechguy

+0

在答案中增加了兩個其他選項。 –