【问题标题】:How to setup routing properly in C# Web API so that incorrect routes will fail?如何在 C# Web API 中正确设置路由,以使不正确的路由失败?
【发布时间】: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


    【解决方案1】:

    以下应该可以工作

    // GET api/solarplants/active
    [HttpGet("Active")]
    public IHttpActionResult Active()
    { ... }
    
    //GET api/solarplants?name=name
    [HttGet]
    public HttpResponseMessage GetByName([FromQuery]string name)
    { ... }
    

    【讨论】:

    • [ActionName] 用于 MVC 而非路由是什么意思?
    • 删除了这一行。把它和另一个混淆了
    猜你喜欢
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多