是的,這個效果很好。只需返回一個JsonResult。
這裏是我在生產中使用的例子:
public partial class StudentController : BaseController {
public StudentController(RESTContext portalContext)
: base(portalContext) { }
[HttpGet, Url("organizations/{organizationId?}/students")]
public virtual JsonResult List(Guid? organizationId) {
if (organizationId != RESTContext.OrganizationId)
throw new HttpNotAuthorizedException();
var query = RESTContext.GetQuery<IQuery<StudentCasesReport>>()
.Where(x => x.OrganizationId, organizationId)
.OrderBy(x => x.LastName, SortOrder.Ascending);
var cases = query.Execute(IsolationLevel.ReadUncommitted);
return Json(cases, JsonRequestBehavior.AllowGet);
}
[HttpGet, Url("organizations/{organizationId?}/students/{studentId?}")]
public virtual JsonResult Get(Guid? organizationId, Guid? studentId) {
if (studentId.IsNull())
throw new HttpNotFoundExecption();
if (organizationId != RESTContext.OrganizationId)
throw new HttpNotModifiedException();
var query = RESTContext.GetQuery<IQuery<StudentCasesReport>>()
.Where(x => x.OrganizationId, organizationId)
.Where(x => x.StudentCaseId, studentId)
.OrderBy(x => x.LastName, SortOrder.Ascending);
var cases = query.Execute(IsolationLevel.ReadUncommitted).FirstOrDefault();
if (cases.IsNull())
throw new HttpNotFoundExecption();
return Json(cases, JsonRequestBehavior.AllowGet);
}
}
這正是我在想什麼。我是網絡服務新手,所以我有點關心最佳實踐。 – 2011-06-02 15:37:25
關於REST ....和MVC的好東西之一。 – ckramer 2011-06-02 15:39:41
您還需要處理404和其他狀態代碼。 MVC3現在給你選擇返回一個狀態碼給用戶。我會推薦AttributeRouteMapper項目來控制控制器級別的路由作爲屬性。使維護更容易。 http://maproutes.codeplex.com/ – 2011-06-02 15:40:13