我有这个ASP.NET MVC 5
项目,正在使用MS Web Api转换为AngularJS。
现在,在旧项目中,我有这些类型的c#控制器Controller
,但是在我的新项目中,我创建了一些新的类型的Web Api控制器ApiController
。
现在,我想在新项目中重用旧的控制器代码。这就是我的困惑。
当我尝试将旧的控制器代码移植到Web Api控制器时,遇到一些前端$http
请求错误。
这是我的AngulardataService
工厂中的一个函数,它使http请求降为'api/Whatif/SummaryPortfolios'
:
function getCurrPortfoliosLIst() {
var deferred = $q.defer();
var url = 'api/Whatif/SummaryPortfolios';
var req={
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/json',
},
data:{}
};
$http(req).then(function (resp){
deferred.resolve(resp.data);
}, function(err){
console.log('Error from dataService: ' + resp);
});
}
但是$http
错误部分返回此异常:
data: Object
ExceptionMessage: "Multiple actions were found that match the request:
↵SummaryPortfolios on type MarginWorkbenchNG.Controllers.WhatifController
↵Post on type MarginWorkbenchNG.Controllers.WhatifController"
ExceptionType: "System.InvalidOperationException"
Message: "An error has occurred."
StackTrace: " at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)
↵ at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)
↵ at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
↵ at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
这是我要调用的c#API控制器,但我需要弄清楚如何创建除直接Get()和Post()方法之外的方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Microsoft.AspNet.Identity;
using NLog;
using Microsoft.AspNet.Identity.Owin;
using MarginWorkbenchNG.Models;
using Rz.DAL;
using Rz.DAL.Integration;
using Rz.DAL.Models;
using Rz.DAL.Models.Rz;
namespace MarginWorkbenchNG.Controllers
{
public class WhatifController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[HttpPost]
public List<WhatifSummaryViewModel> SummaryPortfolios(string filterValue = "", int? whatIfBatchNumber = null, bool includeBaseline = true)
{
// Get portfolios from Rz
IEnumerable<Portfolio> portfolios = GetPortfolios(filterValue, whatIfBatchNumber, includeBaseline)
.Where(x => x.PortfolioKeys.Any(k => k.Type == Settings.Whatif.SidebarPortfolioKey && k.DisplayValue == filterValue));
// View Model
List<WhatifSummaryViewModel> model = new List<WhatifSummaryViewModel> { };
/// additional code here...
return model;
}
}
}
当然,旧的控制器(来自MVC5项目)看起来略有不同,因为该_Summary
方法是类型的ActionResult
并且返回a Partial
:
public class WhatifController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _Summary(string filterValue = "", int? whatIfBatchNumber = null, bool includeBaseline = true)
{
// Get portfolios from Razor
IEnumerable<Portfolio> portfolios = GetPortfolios(filterValue, whatIfBatchNumber, includeBaseline)
.Where(x => x.PortfolioKeys.Any(k => k.Type == Settings.Whatif.SidebarPortfolioKey && k.DisplayValue == filterValue));
// View Model
List<WhatifSummaryViewModel> model = new List<WhatifSummaryViewModel> { };
// additional code removed for brevity...
return PartialView(model.OrderBy(x => x.Title).ThenBy(x => x.SubTitle));
}
我的RouteConfig.cs
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace MarginWorkbenchNG
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
旧项目还使用Html表单提取URL,例如:
<form id="whatif-summary-form" action="@Url.Action("_Summary", "WhatIf")" method="POST"></form>
然后action
在JavaScript(非Angular)中构建ajax请求时拉出attrib以获得URL:
url: form.prop("action")
这是您的整个ApiController吗?您收到的错误消息是因为您的ApiController具有几种相同类型的方法,并且无法确定要路由到哪个方法。要测试这一点,请执行以下操作:注释掉您要调用的控制器方法之外的所有方法。您不应该再收到该错误。
这是一个简单的解决方法,只需告诉Web API如何映射路线即可。将属性[[Route(“ yourroute')]]'添加到您的方法中,它应该可以工作。
public class WhatifController : ApiController
{
[HttpPost, Route("Your Route Goes here 'SummaryPortfolios'")]
public IHttpActionResult SummaryPortfolios(string filterValue = "", int? whatIfBatchNumber = null, bool includeBaseline = true)
{
// Get portfolios from Rz
IEnumerable<Portfolio> portfolios = GetPortfolios(filterValue, whatIfBatchNumber, includeBaseline)
.Where(x => x.PortfolioKeys.Any(k => k.Type == Settings.Whatif.SidebarPortfolioKey && k.DisplayValue == filterValue));
// View Model
List<WhatifSummaryViewModel> model = new List<WhatifSummaryViewModel> { };
/// additional code here...
return Ok(model);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句