将REST搜索端点映射到$资源
ng-resource返回一个包含以下默认资源操作的对象
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
我不确定查询来自AngularJS的REST WebApi端点数据的最佳方法,但是我已经实施了Predicate Builder服务器端以便使用Linq查询我的数据库。 我有一个名为“Search()”@ / api / Product / Search的(POST)端点,它接受一个反序列化的searchCriteria JSON对象,并将其提供给Linq谓词构建器,并针对dbContext执行。 我的WebApi2控制器是这样构建的,使用新的路由属性功能:
[RoutePrefix("Product")]
public class ProductController : ApiController
{
[HttpGet]
[Route("")]
public IEnumerable<Product> Get()
{
try
{
return _productBL.Get();
}
catch
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
[HttpGet]
[Route("{productId}")]
public Product Get(string productId)
{
try
{
var product= _externalWorkStepBL.GetById(productId);
if (product== null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product;
}
catch (Exception)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
[HttpPost]
public HttpResponseMessage Post([FromBody]Product product)
{
try
{
_productBL.Insert(product);
var response = Request.CreateResponse(HttpStatusCode.Created, product);
response.Headers.Location = new Uri(Request.RequestUri, string.Format("Product/{0}", product.workItemID));
return response;
}
catch
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
}
[HttpPost]
[Route("Search")]
public IEnumerable<Product> Where([FromBody] SearchCriteria searchCriteria)
{
if (searchCriteria == null || (searchCriteria.FieldContainsList == null || searchCriteria.FieldEqualsList == null || searchCriteria.FieldDateBetweenList == null))
{
throw new HttpRequestException("Error in, or null, JSON");
}
return _productBL.Where(searchCriteria);
}
[HttpPut]
[Route("")]
public HttpResponseMessage Put([FromBody]Productproduct)
{
try
{
_productBL.Update(product);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Headers.Location = new Uri(Request.RequestUri, string.Format("Product/{0}", product.Id));
return response;
}
catch ()
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
[HttpDelete]
[Route("{productId}")]
public void Delete(string productId)
{
HttpResponseMessage response;
try
{
_productBL.Delete(productId);
response = new HttpResponseMessage(HttpStatusCode.NoContent);
response.Headers.Location = new Uri(Request.RequestUri, string.Format("Product/"));
}
catch (Exception)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
}
}
在客户端,我在$ myResource工厂中封装了$ resource,并添加了一个PUT方法。 然后我使用$ myResource作为我的其他工厂,如下所示:
var app = angular.module('App', ['ngResource'])
.factory('$myResource', ['$resource', function ($resource) {
return function (url, paramDefaults, actions) {
var MY_ACTIONS = {
'update': { method: 'PUT' }
};
actions = angular.extend({}, MY_ACTIONS, actions);
return $resource(url, paramDefaults, actions);
}
}])
.service('ProductFactory', ['$myResource', function ($myResource) {
return $myResource('/api/Product/:productId')
}]);
这很好,但现在我想添加我的搜索端点。 ng-Resource的Angular文档声明一个url可以在action方法中被覆盖,但是我不清楚该怎么做。 我可以将“搜索”操作添加到$ myResource中,但是如何修改ProductFactory中的网址?
.factory('$myResource', ['$resource', function ($resource) {
return function (url, paramDefaults, actions) {
var MY_ACTIONS = {
'update': { method: 'PUT' },
'search': { method: 'POST','params': { searchCriteria: '@searchCriteria' }, isArray: true }
};
actions = angular.extend({}, MY_ACTIONS, actions);
return $resource(url, paramDefaults, actions);
}
}])
就目前而言,调用ProductFactory.search(searchCriteria)会发送一个POST请求,其中包含正确的JSON,但发送给错误的URL“/ api / Product”。 我需要它发布到“/ api / Product / Search”。 如何修改$ myResource使用“api / xxx / Search”,其中xxx是控制器名称?
没关系! 没想到这个工作,但它确实。
.factory('$myResource', ['$resource', function ($resource) {
return function (url, paramDefaults, actions) {
var searchUrl = url + "/Search/:searchCriteria"
var MY_ACTIONS = {
'update': { method: 'PUT' }, //add update (PUT) method for WebAPI endpoint
'search': { method: 'POST', url : searchUrl,'params': { searchCriteria: '@searchCriteria' }, isArray: true } //add Search (POST)
};
actions = angular.extend({}, MY_ACTIONS, actions);
return $resource(url, paramDefaults, actions);
}
}])
链接地址: http://www.djcxy.com/p/89553.html