大家好
我目前在 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);
}
测试来自 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/