WebApi多动作路由不使用AngularJs基于属性的路由

时间:2015-03-29 22:03:39

标签: angularjs asp.net-web-api asp.net-mvc-routing

我正在尝试将以下代码路由到自托管WebApi控制器(ResourcesController)上的操作,但路由不会路由到Delete方法以及 GetAllResources方法。它只适用于一种方法,但不适用于两种方法。我正在使用基于属性的路由。任何帮助都乐意接受!

  1. 使用以下Web-Api自托管启动代码:

    使用DomainEntities; 使用Owin; 使用WebApiContrib.Formatting.Jsonp;

    命名空间ResourcesWebApiHost {     公共课启动     {         public void Configuration(IAppBuilder app)         {                 var webApiConfiguration = ConfigureWebApi();                 app.UseWebApi(webApiConfiguration);         }

        private HttpConfiguration ConfigureWebApi()
        {
            var config = new HttpConfiguration();
            var corsAttr = new EnableCorsAttribute("http://localhost:5000/", "*", "*");
            config.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));
            config.EnableCors();
            config.Filters.Add(new CrossDomainAccessFilter());
            config.MapHttpAttributeRoutes();
            return config;
        }
    
        public class CrossDomainAccessFilter : ActionFilterAttribute
        {
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                var routes = actionContext.Request.GetRouteData();
                base.OnActionExecuting(actionContext);
            }
    
            public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
            {
                if (actionExecutedContext.Response.Content != null)
                {
                    actionExecutedContext.Response.Content.Headers.Add("Access-Control-Allow-Origin", "null");
                    actionExecutedContext.Response.Content.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                    actionExecutedContext.Response.Content.Headers.Add("Access-Control-Allow-Headers","Content-Type, X-Requested-With");
                }
            }
        }
    }
    

    }

  2. 使用以下控制器:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Runtime.InteropServices.ComTypes;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Http;
    using DomainEntities;
    using Interfaces;
    using ResourceManagerService;
    
    namespace ResourcesWebApiHost
    {
    
    
    public class ResourcesController : ApiController
    {
        [Route("api/Resources/GetAllResources")]
        [HttpGet]
        public List<Resource> GetAllResources()
        {
            var service = new Service();
            return service.GetAllResources();
        }
    
        [ActionName("api/Resources/Delete")]
        [HttpPost]
        public HttpResponseMessage Delete(List<Resource> resources)
        {
            var service = new Service();
            var success = service.Delete(resources);
            var result = Request.CreateResponse(HttpStatusCode.OK,                  success.ToString());
            return result;
        }
    }
    

    }

  3. 使用以下AngularJs代码:

            var appUrl =&#34; http://localhost:5001/api/Resources&#34 ;;         var model = {};

        var resourcesApp = angular.module("resourcesApp", []);
    
        resourcesApp.run(function ($http) {
            $http.defaults.headers.put = {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
            };
            $http.defaults.useXDomain = true;
    
            $http.get('http://localhost:5001/api/Resources/GetAllResources').success(function (data) {
                model.resources = data;
            }).error(function (data, status) {
                alert('ERROR ' + (data || 'No Error Description'));
            });
        });
    
        resourcesApp.filter("selectedItems", function () {
            return function (items) {
                var resultArr = [];
                angular.forEach(items, function (item) {
                    if (item.mustDelete == true) {
                        resultArr.push(item);
                    }
                });
                return resultArr;
            }
        });
    
        resourcesApp.controller("resourcesCtrl", function ($scope, $http) {
            $scope.theModel = model;
            $scope.close = function () {
                window.close();
            }
            $scope.deleteSelectedItems = function () {
                $http.defaults.useXDomain = true;
                $http.post('http://localhost:5001/api/Resources/Delete', $scope.theModel.resources);
            }
        });
    </script>
    

1 个答案:

答案 0 :(得分:0)

通过将[EnableCors(起源:“”,标题:“”,方法:“*”)]标题添加到我的控制器类来解决问题。新代码如下:

namespace ResourcesWebApiHost
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class ResourcesController : ApiController
    {//...more code follows...

我正在使用CORS进行跨源请求,但我只实现了配置部分 - 我省略了将属性添加到类中,从而完成了enable-CORS实现。

有关详细信息,此问题与ASP.Net WebApi路由系统有关,与AngularJS代码无关。