我正在将 .NET Framework 应用程序移植到 .NET Core 中。我已通过 NuGet System.ServiceModel.Web 添加,但似乎不起作用。我需要“WebGet”的替代方案:
[ServiceContract]
public interface IChannelsApi
{
[WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json), OperationContract]
List<Channel> GetChannels();
[WebGet(UriTemplate = "{name}", ResponseFormat = WebMessageFormat.Json), OperationContract]
Channel GetChannel(string name);
}
我必须做什么?
正如 @Thomas 所指出的,WebGet 早已被用于创建 REST API 的更好的框架所取代。如果您还没有准备好,请在 VS2015 / VS2017 中创建一个新的 .Net Core Web Api 项目,运行它,然后看看它与旧的 WCF 方法有何不同。您会注意到需要的样板代码和装饰要少得多。Here's https://stackoverflow.com/a/9452105/2869344WCF 和 ASP.NET Web API 之间的一些差异的概述,.Net Core 实际上只是下一代。
下面是来自工作控制器类的一些代码的更全面的示例。如果需要,您可以将其抽象为接口,但是可能没有意义 https://stackoverflow.com/a/15411734/2869344。还要注意缺少[ServiceContract]
and [OperationContract]
装饰品等。只需指定[Route(...)]
(可选 - 如果控制器不符合默认路由),以及使用的方法和 Uri 路径[HttpGet(...)]
, etc.
此代码还假设了一些事情,例如向 DI 容器注册依赖项(ILogger
and ICustomerRepository
)。请注意,.Net Core 内置了依赖注入,这是一个很好的功能(快速概述 https://jonhilton.net/2016/11/17/start-using-dependency-injection-asp-net-core/).
最后我还推荐使用Swagger http://swagger.io/如果你还没有。我在这方面迟到了,但最近一直在使用它,它对 API 开发来说是一个福音(下面的广泛评论有助于使 Swagger 更有用):
[Route("api/[controller]")]
public class CustomersController : Controller
{
ILogger<CustomersController> log;
ICustomerRepository customerRepository;
public CustomersController(ILogger<CustomersController> log, ICustomerRepository customerRepository)
{
this.log = log;
this.customerRepository = customerRepository;
}
/// <summary>
/// Get a specific customer
/// </summary>
/// <param name="customerId">The id of the Customer to get</param>
/// <returns>A customer with id matching the customerId param</returns>
/// <response code="200">Returns the customer </response>
/// <response code="404">If a customer could not be found that matches the provided id</response>
[HttpGet("{customerId:int}")]
[ProducesResponseType(typeof(ApiResult<Customer>), 200)]
[ProducesResponseType(typeof(ApiResult), 404)]
public async Task<IActionResult> GetCustomer([FromRoute] int customerId)
{
try
{
return Ok(new ApiResult<Customer>(await customerRepository.GetCustomerAsync(customerId)));
}
catch (ResourceNotFoundException)
{
return NotFound(new ApiResult($"No record found matching id {customerId}"));
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)