2012-05-21 136 views
1

我正在創建一個ASP.NET MVC3寧靜的Web服務,以允許從一組服務器上傳報告。當創建一個新的報告,我希望客戶端應用程序做一個PUT到MVC3 REST服務 - 如何訪問PUT或POST請求的請求主體內容?

傳遞報告的內容作爲XML的請求的主體。

我的問題是:如何訪問我的控制器中的報告內容?我會想象它在HttpContext.Request對象的某個地方可用,但我不願意從我的控制器訪問它,因爲它不可能(?)單元測試。是否可以調整路由以允許將內容作爲一個或多個參數傳遞到控制器方法中?結果必須是RESTful,即必須將PUT或POST發佈到上面的URL。

目前我的路由:

routes.MapRoute(
    "SaveReport", 
    "Servers/{serverName}/Reports/{reportTime", 
    new { controller = "Reports", action = "Put" }, 
    new { httpMethod = new HttpMethodConstraint("PUT") }); 

有什麼辦法來修改這個從HTTP請求主體的內容傳遞到控制器方法? 控制器方法目前:

public class ReportsController : Controller 
{ 
    [HttpPut] 
    public ActionResult Put(string serverName, string reportTime) 
    { 
     // Code here to decode and save the report 
    } 
} 

我試圖把該URL的對象是:

public class Report 
{ 
    public int SuccessCount { get; set; } 
    public int FailureOneCount { get; set; } 
    public int FailureTwoCount { get; set; } 
    // Other stuff 
} 

This question看起來相似,但沒有任何回答。 在此先感謝

回答

1

好像你只需要使用標準ASP.NET MVC model binding功能與輕微的皺紋,你會做一個HTTP PUT,而不是更常見的HTTP POST。這article series有一些很好的樣本,看看如何使用模型綁定。然後

控制器代碼看起來像:

public class ReportsController : Controller 
{ 
    [HttpPut] 
    public ActionResult Put(Report report, string serverName, string reportTime) 
    { 
     if (ModelState.IsValid) 
     { 
      // Do biz logic and return appropriate view 
     } 
     else 
     { 
      // Return invalid request handling "view" 
     } 
    } 
} 

編輯:==================== >>>

喬恩添加這個代碼他的評論作爲修訂的一部分,所以我把它添加到答案爲他人:

創建自定義模型綁定器:

public class ReportModelBinder : IModelBinder 
{ 
    public object BindModel(
     ControllerContext controllerContext, 
     ModelBindingContext bindingContext) 
    { 
     var xs = new XmlSerializer(typeof(Report)); 
     return (Report)xs.Deserialize(
      controllerContext.HttpContext.Request.InputStream); 
    } 
} 

修改Global.asax.cs註冊該報告類型的此模型聯編程序:

ModelBinders.Binders[typeof(Report)] = new Models.ReportModelBinder(); 
+1

Thanks Sixto。這足以阻止我攪動並讓我朝着正確的方向前進。你的建議也讓我去[本文](http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx)哪也有幫助。 –

+0

我添加到控制器方法簽名的報告,則創建的自定義模型綁定器: 公共類ReportModelBinder:IModelBinder { 公共對象BindModel(ControllerContext controllerContext,ModelBindingContext的BindingContext) { 變種XS =新的XmlSerializer(typeof運算(報告) ); return(Report)xs。反序列化(controllerContext.HttpContext.Request.InputStream); } } 最後,我修改了Global.asax.cs中登記針對報告類型這個模型粘合劑: ModelBinders.Binders [typeof運算(報告)] =新Models.ReportModelBinder(); –