C# - 使用 Refit 传递 Web Api 对象

标签 c# asp.net-core xamarin asp.net-web-api refit

大家好

我目前在 Xamarin 工作,并被基本操作困扰。我正在尝试使用 Refit 从 Xamarin 调用我的 NetCore Web API。

主要问题是 - 我猜 - 我想在调用参数中传递对象。第二个问题可能是该对象有一个枚举列表作为属性。

型号:

public class ArticleFilter
{
    public List<ArticleType> Types { get; set; }

    public int? CarBrandId { get; set; }
}

public enum ArticleType
{
    News = 1,
    SpecialOffer = 2,
    Service = 3,
}

retrofit 界面:

[Headers("Content-Type: application/json")]
public interface IArticleApi
{        
    [Get("/api/articles")]
    [Headers("Content - Type: application / json")]
    Task<List<Article>> GetAll(ArticleFilter filter);

    [Get("/api/articles/{id}")]
    Task<ArticleDetail> GetOne(int id);
}

API Controller :

    [HttpGet]
    public async Task<IActionResult> GetAll([FromUri] ArticleFilterDto filter)
    {
        var articles = await _articleSectionService.GetAll(filter);

        if (articles == null)
        {
            return NotFound();
        }                

        return Ok(articles);
    }

postman 调用: enter image description here

测试来自 Xamarin View 模型的调用:

var filter = new ArticleFilter()
{
    Types = new List<ArticleType> { ArticleType.News }
};
               
var test = new List<Article>();
test = await response.GetAll(filter);

实际上这个属于异常(exception) - 415 - 不支持的媒体类型

我看到了他们的 GitHub 文档,但仍然没有任何进展。请一些超人帮助我吗?

最佳答案

终于解决了

以防万一有人遇到同样的情况。就我而言,从接口(interface)中的 [Body]/[FromUri] 更改为 [Query] 以及 Controller 方法中的 [FromQuery] 解决了我的问题。

[Headers("Content-Type: application/json")]
public interface IArticleApi
{
    [Get("/api/articles/")]       
    Task<List<Article>> GetAll([Query]ArticleFilterDto filter);
}

[HttpGet]
public async Task<IActionResult> GetAll([FromQuery]ArticleFilterDto filter)
{
   var articles = await _articleSectionService.GetAll(filter);

   if (articles == null)
   {
       return NotFound();
   }                

   return Ok(articles);
}

关于C# - 使用 Refit 传递 Web Api 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67330071/

相关文章:

xamarin - Xamarin 表单中的响应式字体大小

android - 多行中的更多 TextView

c# - Xamarin 无法调试 (Android)

c# - 如何格式化汉字以适合列?

c# - 为什么我要使用 HashSet 而不是 Dictionary?

c# - 错误 : Cannot implicitly convert type 'void' to 'System.Collections.Generic.List'

asp.net-core - 异常处理和从 View 组件重定向

javascript - .net core 2.2 和 3.0 中的差异帖子结构

c# - 如何在 MVC 中读取 DataSourceRequest 以进行过滤和排序

asp.net - 如何在 ASP.NET 中使用多个授权方案颁发相应的 Bearer 和 Cookie 标识?