将ODataRoutePrefix和ODataRoute用于OData AttributeRouting不起作用 [英] using ODataRoutePrefix and ODataRoute for OData AttributeRouting is not working

查看:54
本文介绍了将ODataRoutePrefix和ODataRoute用于OData AttributeRouting不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:这不是重复的,因为我在 AspNetCore 中使用了 OData 的全新实现版本.

Note: This is not a duplicate since I'm using a completely new implementation version of OData in AspNetCore.

基于微软撰写的令人困惑的文章,我试图使用 AttributeRoutingConvetion ,并最终使用 ODataRoutePrefix ODataRoute 使用Asp.net Core 5路由OData请求Web API和 Microsoft.AspNetCore.OData Version ="8.0.0-preview3" (请注意 版本).

Based on this confusing article by Microsoft, I'm trying to use AttributeRoutingConvetion and ultimately using ODataRoutePrefix and ODataRoute to route OData requests using Asp.net Core 5 Web API and Microsoft.AspNetCore.OData Version="8.0.0-preview3"(please pay attention to version).

这是我的代码:

Startup.cs

 public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
           

            services.TryAddEnumerable(ServiceDescriptor.Transient<IODataControllerActionConvention, AttributeRoutingConvention>());
            services.AddOData(
                opt => opt.AddModel("odata",GetEdmModel()).Select().Count().Filter().OrderBy().SetAttributeRouting(true)
                );
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        public IEdmModel GetEdmModel()
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<WeatherForecast>("WeatherForecast2");
            return builder.GetEdmModel();
        }

这是我的控制器:

    [ODataRoutePrefix("WFC")]
    public class WeatherForecast2Controller : ODataController
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecast2Controller> _logger;

        public WeatherForecast2Controller(ILogger<WeatherForecast2Controller> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        [EnableQuery]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }


        [HttpGet]
        [EnableQuery]
        [ODataRoute("AnotherGet")]
        public IEnumerable<WeatherForecast> AnotherGet()
        {
            var rng = new Random();
            return Enumerable.Range(1, 3).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

现在,我期望通过执行AnotherGet方法来调用https://localhost:44346/WFC/AnotherGet返回3 Weatherforcast结果,但是却出现404错误.我还尝试了以下方法:

Now what I expect is calling the https://localhost:44346/WFC/AnotherGet return the 3 Weatherforcast result by executing AnotherGet method but I get a 404 error. I have also tried the followings:

~/odata/WeatherForecast2  -  executes Get and returns array of 5 Weatherforcast 
~/odata/WFC/              - 404 not found 
~/odata/WFC/AnotherGet    - 404 not found 
~/WFC/                    - 404 not found 
~/WFC/AnotherGet          - 404 not found 

如何执行特定的控制器及其方法?

How can I execute a specific controller and its method ?

推荐答案

@nAvid

感谢您尝试使用ASP.NET Core OData 8.0.

Thanks for trying ASP.NET Core OData 8.0.

首先,我在博客中提到:

First, in the blog, I mentioned:


 1. ODataRoutePrefixAttribute is an attribute that can, and only can be placed on an OData controller to specify the prefix that will be used for all actions of that controller.
 2. ODataRouteAttribute is an attribute that can, and only can be placed on an action of an OData controller to specify the OData URLs that the action handles.

第二,路径路由模板" 应该遵循OData约定规范.也就是说,"ODataRoutePrefixAttribute"和"ODataRouteAttribute"中的串联字符串应通过OData uri解析器.

Second, the path route template defined in the attribute should follow up OData convention spec. That is, the concatenated string from 'ODataRoutePrefixAttribute' and 'ODataRouteAttribute' should pass the OData uri parser.

例如:

[ODataRoutePrefix("WFC")] 
public class WeatherForecast2Controller : ODataController
{
  ...
   [ODataRoute("AnotherGet")]
   public IEnumerable<WeatherForecast> AnotherGet()
   {
   }
}

动作"AnotherGet"的串联字符串是"WFC/AnotherGet".来自 OData约定URI WFC/AnotherGet 应该是有效的OData URI(模板).但是,Edm模型(您在GetEdmModel中内置)没有任何与"WFC"相关的内容.或"AnotherGet".

The concatenated string for action 'AnotherGet' is "WFC/AnotherGet'. From OData convention URI, WFC/AnotherGet should be a valid OData URI (template). BUT, the Edm model (you built in GetEdmModel) doesn't have anything related "WFC" or "AnotherGet".

因此,预计您将收到以下响应:

So, It's expected that you will get the following response:

  • 〜/odata/WFC/-404未找到
  • 〜/odata/WFC/AnotherGet-找不到404
  • 〜/WFC/-404未找到
  • 〜/WFC/AnotherGet-找不到404

对于

  • '〜/odata/WeatherForecast2-执行Get,并返回5个Weatherforcast数组',

这不是OData属性路由,但是可以工作,因为它是OData约定路由.约定路由看起来像"EntitySetName".+控制器为控制器.因此,公共类WeatherForecast2Controller 符合该约定.和 public IEnumerable< WeatherForecast>Get()符合查询实体集约定路由.因此,它有效.

that's not OData attribute routing, however it works because it's OData convention routing. The convention routing looks the "EntitySetName" + Controller for the controller. So, public class WeatherForecast2Controller meets that convention. and public IEnumerable<WeatherForecast> Get() meets the query entity set convention routing. So, it works.

这篇关于将ODataRoutePrefix和ODataRoute用于OData AttributeRouting不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆