我在 OData V4 中遇到属性路由问题。我有一个简单的客户模型类和一个控制器,它有 2 个 Get 方法。但是,每当我尝试获取特定的 Customer like/Customers(7)
时,它总是使用第二个 Get 方法来获取所有客户,但从不使用 id 参数闯入该方法。我在这里想念什么?谢谢!
控制器:
using System.Data;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.OData;
using System.Web.OData.Routing;
using API.Models;
namespace API.Controllers
{
public class CustomersController : ODataController
{
private OContext db = new OContext();
// GET: Customers(5)
[HttpGet]
[ODataRoute("Customers({id:int})")]
[EnableQuery]
public SingleResult<Customers> Get([FromODataUri] int id)
{
IQueryable<Customers> result = db.Customers.Where(p => p.Id == id).AsQueryable();
return SingleResult.Create(result);
}
// GET: Customers
[HttpGet]
[ODataRoute("Customers")]
[EnableQuery]
public IQueryable<Customers> Get()
{
return db.Customers.AsQueryable();
}
}
}
WebApiConfig:
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using API.Models;
using Microsoft.OData.Edm;
namespace API
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.MapHttpAttributeRoutes();
config.MapODataServiceRoute("odata", null, GetEdmModel());
config.EnsureInitialized();
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.Namespace = "API.Controllers";
builder.ContainerName = "DefaultContainer";
builder.EntitySet<Customers>("Customers").EntityType.HasKey(c => c.Id);
builder.EntitySet<Customers_CustomField> ("Customers_CustomFields");
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
}