简体   繁体   中英

How to setup routing properly in C# Web API so that incorrect routes will fail?

I'm trying to create my Web API in ASP.NET 2.5 so that I may call a URL like http://localhost:8080/api/solarplant/active to call the Active method below and http://localhost:8080/api/solarplant?name=SiteNameHere for the GetByName method.

When I call just http://localhost:8080/api/solarplant , it appears it's also calling the Active method and when I call the Active method with the query parameter of "name" it works. How can I get my URLs to work only as described above in the first paragraph, and to work like that only? I don't want to call just /solarplant or to be able to add the name parameter at the end of the Active call and get results.

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;
    }
}

}

Following should work

// GET api/solarplants/active
[HttpGet("Active")]
public IHttpActionResult Active()
{ ... }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM