我正在将 .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);
}
Run Code Online (Sandbox Code Playgroud)
我必须做什么?
正如@Thomas 所指出的,WebGet 长期以来一直被用于创建 REST API 的更好的框架所取代。如果您还没有,请在 VS2015 / VS2017 中创建一个新的 .Net Core Web Api 项目,运行它,然后看看它与旧的 WCF 方法有何不同。您会注意到需要的样板代码和装饰要少得多。以下是WCF 和 ASP.NET Web API 之间一些差异的概要,.Net Core 实际上只是它的下一代。
下面是来自工作控制器类的一些代码的更全面的示例。如果需要,您可以将其抽象为一个接口,但可能没有意义。还要注意缺少[ServiceContract]和[OperationContract]装饰等。只需指定[Route(...)](可选 - 如果控制器不符合默认路由),以及使用的方法和 Uri 路径[HttpGet(...)]等。
此代码还假设了一些事情,例如使用 DI 容器(ILogger和ICustomerRepository)注册的依赖项。请注意,.Net Core 内置了依赖注入,这是一个不错的功能(快速概述)。
最后,如果您还没有使用Swagger,我还建议您使用。我迟到了,但最近一直在使用它,这对 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}"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9584 次 |
| 最近记录: |