我已将WebApi添加到现有MVC应用程序并使用post方法创建控制器。我在webapiconfig中配置了一个路由。当我使用Fiddler发布到控制器时,我收到“多个操作”错误。我的ApiConfig和Controller发布在下面。 Ninject有一些Ioc和DI正在进行中。我是否需要添加不同的路由定义,或者这是关于要发布的数据?
webapiconfig.cs
public static void Register(HttpConfiguration config)
{
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Routes.MapHttpRoute(
name: "Materials",
routeTemplate: "api/materials/{id}",
defaults: new { controller = "materials", id = RouteParameter.Optional }
);
}
MaterialController。
using ????.Info.DAL;
using ????.Info.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using IdentitySample.Models;
namespace ????.Info.Controllers.Api
{
public class MaterialsController : BaseApiController
{
public MaterialsController(I????Repository repo)
:base(repo)
{
}
[Route("api/materials/")]
public IEnumerable<MaterialModel> Get()
{
IQueryable<MaterialEntities.Materials> query;
query = TheRepository.GetAllMaterials();
var results = query
.ToList()
.Select(s => TheModelFactory.Create(s));
return results;
}
[Route("api/materials/{id:int}")]
public HttpResponseMessage GetMaterial(int id)
{
try
{
var material = TheRepository.GetMaterial(id);
if (material != null)
{
return Request.CreateResponse(HttpStatusCode.OK, TheModelFactory.Create(material));
}
else
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
[HttpPost]
public HttpResponseMessage Post([FromBody] MaterialModel materialModel)
{
try
{
var entity = TheModelFactory.Parse(materialModel);
if (entity == null) Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not read MaterialType/Organization from body");
if (TheRepository.Insert(entity) && TheRepository.SaveAll())
{
return Request.CreateResponse(HttpStatusCode.Created, TheModelFactory.Create(entity));
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Could not save to the database.");
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
public MaterialEntities.Materials Parse(MaterialModel materialmodel)
{
try
{
var material = new MaterialEntities.Materials()
{
Name = materialmodel.Name,
Description = materialmodel.Description,
DateCreated = materialmodel.DateCreated,
};
return material;
}
catch (Exception)
{
return null;
}
}
}
}
答案 0 :(得分:0)
好的,谢谢你的帮助。通过将config.MapHttpAttributeRoutes();
添加到WebApiConfig来解决此问题。我删除了默认路由定义,因为我将使用AttributeRouting并且它现在正在工作。
更新:看起来可以在WebApiConfig中混合属性和约定路由,如所讨论here所以我的问题通过向WebApiConfig添加config.MapHttpAttributeRoutes();
来解决