我有一个 mvc 4 应用程序。我正在迁移我的一些逻辑以使用 Web API。我无法使ChangeState
方法在以下代码中工作(未找到 404 文件)。我看到那个帖子:
我正在考虑为状态制作一个不同的控制器,因为它是不同的实体,但我很好奇如何让它适用于这种情况。
public class FranchiseController : ApiController
{
[DataContext]
public IEnumerable<FranchiseInfoViewModel> GetAllFranchises()
{
var allFranchises = new List<FranchiseInfoViewModel>();
var franchiseInfoList = _franchiseService.GetAll();
foreach (var franchiseInfo in franchiseInfoList)
{
allFranchises.Add(new FranchiseInfoViewModel(franchiseInfo, p => p.IsImportant));
}
return allFranchises;
}
[DataContext]
[System.Web.Http.HttpPost]
public string ChangeState(int franchiseId, FranchiseProductionStates state)
{
_franchiseService.ChangeProductionState(franchiseId, state);
var redirectToUrl = "List";
return redirectToUrl;
}
[DataContext]
public FranchiseInfoViewModel GetFranchise(int? franchiseId)
{
var realId = franchiseId ?? default(int);
var franchiseInfo = _franchiseService.CreateOrGet(realId);
var franchiseInfoViewModel = new FranchiseInfoViewModel(franchiseInfo, p => true);
return franchiseInfoViewModel;
}
}
这是我的路线:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"\d*" }
);
config.Routes.MapHttpRoute(
name: "DefaultApiPlusActionAndFolderid",
routeTemplate: "api/{controller}/{action}/{franchiseId}/{state}",
defaults: null,
constraints: new { action = @"[a-zA-Z]+", franchiseId = @"\d+", state = @"[a-zA-Z]+" }
);
和我调用动作方法的js代码:
var changeState = function (franchiseId, state) {
var deferred = $.Deferred();
amplify.request({
resourceId: 'changeState',
success: deferred.resolve,
error: deferred.reject,
data: { franchiseId: franchiseId, state: state }
});
return deferred;
};
amplify.request.define('changeState', 'ajax', {
url: "/api/franchise/ChangeState",
type: "POST",
dataType: 'json',
decoder: errorsDecoder
});
注意:
FranchiseProductionStates
是枚举类型。欢迎任何建议。这是我第一次使用 web api。谢谢!