正如@Thomas指出的那樣,WebGet早已被用於創建REST API的更好的框架所取代。如果還沒有,請在VS2015/VS2017中創建一個新的.Net Core Web Api項目,運行它,然後查看它與舊的WCF方法的不同之處。您會注意到需要更少的樣板代碼和裝飾。 Here's WCF和ASP.NET Web API之間的一些差異的概要,而.Net Core實際上就是下一代。
下面是來自工作控制器類的一些代碼的更全面的例子。如果需要,可以將此抽象爲一個接口,但there's probably no point。另外請注意缺少[ServiceContract]
和[OperationContract]
裝飾品等等。只需指定[Route(...)]
(可選 - 如果控制器不符合默認路由)以及使用[HttpGet(...)]
等的方法和Uri路徑。
此代碼還假定一些內容,例如向DI註冊的相關性容器(和ICustomerRepository
)。請注意.Net Core內置了依賴注入,這是一個很好的功能(Quick rundown)。
最後,我還建議如果您還沒有使用Swagger。我來晚了就這一個黨,但近來使用它了,它是API開發的福音(廣泛的評論如下助攻使揚鞭更有用):
[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}"));
}
}
}
你能不能給我們一個[MCVE ]?帶有一個GET方法的簡單控制器類,您嘗試過的方法無效。 – pcdev
這是一個界面。我已經提供了更多的代碼。 – Gicminos