我正在将 .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 WCF 和 ASP.NET Web API 之间的一些差异的概述,.Net Core 实际上只是下一代。
下面是来自工作 Controller 类的一些代码的更全面的示例。如果需要,您可以将其抽象为接口(interface),但是 there's probably no point 。另请注意,缺少 [ServiceContract]
和 [OperationContract]
装饰等。只需指定 [Route(...)]
(可选 - 如果 Controller 不符合默认路由),以及使用 [HttpGet(...) 的方法和 Uri 路径)]
等
此代码还假设了一些事情,例如向 DI 容器(ILogger
和 ICustomerRepository
)注册依赖项。请注意,.Net Core 内置了依赖注入(inject),这是一个很好的功能( Quick rundown )。
最后,我还建议使用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}"));
}
}
}
关于c# - 系统.ServiceModel.Web .NET Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44562141/