Iva*_*ono 8 c# odata asp.net-web-api
我已经开始在我的WebAPi2项目中包含OData(目前在我的开发机器上的IIS8 Express中托管).我的OData配置类看起来像这样:
public class ODataConfig
{
private readonly ODataConventionModelBuilder modelBuilder;
public ODataConfig()
{
modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Category>("Category");
}
public IEdmModel GetEdmModel()
{
return modelBuilder.GetEdmModel();
}
}
Run Code Online (Sandbox Code Playgroud)
然后我在WebApiConfig类中添加了以下内容:
ODataConfig odataConfig = new ODataConfig();
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: "MyServer/OData",
model: odataConfig.GetEdmModel(),
defaultHandler: sessionHandler
);
Run Code Online (Sandbox Code Playgroud)
并从一个基本的控制器开始,只有一个动作,如下所示:
public class CategoryController : ODataController
{
[HttpGet]
public IHttpActionResult Get([FromODataUri] int key)
{
var entity = categoryService.Get(key);
if (entity == null)
return NotFound();
return Ok(entity);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在我的HttpClient中,请求URL看起来像这样:MyServer/OData/Category(10)
但是,我收到以下错误:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/MyServer/OData/Category(10)'.","MessageDetail":"No type was found that matches the controller named 'OData'."}
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
编辑
如果我将routePrefix设置为null或'odata'并相应地更改我的请求URL,则请求正常.所以这意味着我不能拥有像'myServer/odata'这样的路由前缀.
这是OData标准命名约定吗?如果是的话,它可以被覆盖吗?
我一直在使用WebApiConfig.Register()Web API 项目中默认包含的相同方法,并使用以下内容进行传递:
var builder = new ODataConventionModelBuilder();
// OData entity sets..
builder.EntitySet<Seat>("Seats");
builder.EntitySet<Table>("Tables");
// Configure the Route
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
Run Code Online (Sandbox Code Playgroud)
第一个参数是一个友好的名称,第二个参数是您想要的名称!您可以将其更改为您想要的任何内容。
更新:如果您使用 OData V4,路由将按如下方式初始化:
config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
如果您使用的是 V4,现在可以通过使用属性进行基于方法的路由(想想 Nancy 风格)
您可以在 OWIN 启动类或 Global.asax 中使用它。无论哪种方式对我来说都很好。
请参阅: http: //www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/creating-an-odata-endpoint