在的WebAPI解决接口 [英] Resolving interfaces in WebAPI

查看:169
本文介绍了在的WebAPI解决接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器方法具有以下签名

I have a controller method with the following signature

[HttpGet]
[Route("results")]
public List<IResult> GetResults()
{
  return repo.GetResults();
}

这并不奇怪,我得到一个JSON的.NET异常说JSON .NET解决不了IResult到一个具体类型。有没有一种方法来提供JSON .NET的具体类(结果),所以我没有改变方法的singature?

Not surprisingly, I get a JSON .NET exception saying JSON .NET can't resolve IResult to a concrete type. Is there a way to provide JSON .NET the concrete class (Result) so I don't have to change the singature of the method?

推荐答案

好像你想做的事是不是真的依赖注入,而是要控制如何对数据序列化。这是完全使用自定义的媒体类型格式(的 http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters ),但你需要先删除默认JSON格式(<一href="http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_media_type_formatter" rel="nofollow">http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_media_type_formatter).

It seems like what you want to do isn't really dependency injection but instead you want to control how the data is serialized. This is completely within your control using a custom media-type formatter (http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters), however you would need to remove the default json formatter first (http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_media_type_formatter).

这都可以做但它使事情变得更加脆弱,可能不是你想要的解决方案。如果客户希望XML(你可以替换格式太)它不会工作。但更重要的是,如果你在你的容器中注册接口的两种实现方式会发生什么?这带来了另一个问题,为什么您使用的接口作为DTO?接口通常定义的方法的集合到由消费者来实现。据我所知,性能也可以定义,但我不认为这是一个预期的使用接口。

This can all be done however it will makes things more brittle and is probably not the solution you want. It won't work if the client wants xml (you could replace that formatter too). But more importantly, what happens if you have two implementations of the Interface registered in your container? This brings up another question, why are you using an interface as a DTO? An interface typically defines a collection of methods to be implemented by a consumer. I understand that properties can also be defined, but I don't think this is an intended use of interfaces.

这篇关于在的WebAPI解决接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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