【发布时间】:2018-03-02 22:29:10
【问题描述】:
我正在尝试在 ASP.NET 2.5 中创建我的 Web API,以便我可以调用像 http://localhost:8080/api/solarplant/active 这样的 URL 来调用下面的 Active 方法,并使用 http://localhost:8080/api/solarplant?name=SiteNameHere 来调用 GetByName 方法。
当我只调用http://localhost:8080/api/solarplant 时,它似乎也在调用Active 方法,而当我使用查询参数“name”调用Active 方法时,它会起作用。我怎样才能让我的 URL 只能按照上面第一段中的描述工作,并且只能这样工作?我不想只调用 /solarplant 或能够在 Active 调用结束时添加 name 参数并获得结果。
using SolarFaultValidationService.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace SolarFaultValidationService.Controllers
{
[RoutePrefix("api/solarplants")]
public class SolarPlantController : ApiController
{
private SolarPlantRepository solarPlantRepository;
public SolarPlantController()
{
this.solarPlantRepository = new SolarPlantRepository();
}
// GET api/solarplants
[ActionName("Active")]
[HttpGet]
public IHttpActionResult Active()
{
string data = solarPlantRepository.GetActiveSolarPlants();
HttpResponseMessage httpResponse = Request.CreateResponse(HttpStatusCode.OK, data);
return ResponseMessage(httpResponse);
}
//GET api/solarplants/sitenamehere
[Route("{name:string}")]
public HttpResponseMessage GetByName(string name)
{
string response = solarPlantRepository.GetSolarPlantByName(name);
HttpResponseMessage httpResponse = Request.CreateResponse(HttpStatusCode.OK, response);
return httpResponse;
}
}
}
【问题讨论】:
标签: c# asp.net-web-api routing