c# - 找到与请求匹配的多个操作

标签 c# asp.net-web-api asp.net-mvc-routing

<分区>

我已经阅读了很多关于路由和 Controller 的问题,但我就是找不到我要找的东西。我有这个结构如下的 Controller :

更新:包括完整的类(class)源。

public class LocationsController : ApiController
{
    private readonly IUnitOfWork _unitOfWork;

    public LocationsController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    // GET /api/locations/id
    public Location Get(Guid id)
    {
        return this.QueryById<Location>(id, _unitOfWork);
    }

    // GET /api/locations
    public IQueryable<Location> Get()
    {
        return this.Query<Location>(_unitOfWork);
    }

    // POST /api/locations
    public HttpResponseMessage Post(Location location)
    {
        var id = _unitOfWork.CurrentSession.Save(location);
        _unitOfWork.Commit();

        var response = Request.CreateResponse<Location>(HttpStatusCode.Created, location);
        response.Headers.Location = new Uri(Request.RequestUri, Url.Route(null, new { id }));

        return response;
    }

    // PUT /api/locations
    public Location Put(Location location)
    {
        var existingLocation = _unitOfWork.CurrentSession.Query<Location>().SingleOrDefault(x => x.Id == location.Id);

        //check to ensure update can occur
        if (existingLocation == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        //merge detached entity into session
        _unitOfWork.CurrentSession.Merge(location);
        _unitOfWork.Commit();

        return location;
    }

    // DELETE /api/locations/5
    public HttpResponseMessage Delete(Guid id)
    {
        var existingLocation = _unitOfWork.CurrentSession.Query<Location>().SingleOrDefault(x => x.Id == id);

        //check to ensure delete can occur
        if (existingLocation != null)
        {
            _unitOfWork.CurrentSession.Delete(existingLocation);
            _unitOfWork.Commit();
        }

        return new HttpResponseMessage(HttpStatusCode.NoContent);
    }

    // rpc/locations
    public HttpResponseMessage Dummy()
    {
        // I use it to generate some random data to fill the database in a easy fashion
        Location location = new Location();
        location.Latitude = RandomData.Number.GetRandomDouble(-90, 90);
        location.Longitude = RandomData.Number.GetRandomDouble(-180, 180);
        location.Name = RandomData.LoremIpsum.GetSentence(4, false);

        var id = _unitOfWork.CurrentSession.Save(location);
        _unitOfWork.Commit();

        var response = Request.CreateResponse<Location>(HttpStatusCode.Created, location);
        response.Headers.Location = new Uri(Request.RequestUri, Url.Route(null, new { id }));

        return response;
    }
}

还有我的路由定义(Global.asax):

public static void RegisterRoutes(RouteCollection routes)
{
    // Default route
    routes.MapHttpRoute(
        name: "Default",
        routeTemplate: "{controller}/{id}",
        defaults: new { id =  RouteParameter.Optional }
    );

    // A route that enables RPC requests
    routes.MapHttpRoute(
        name: "RpcApi",
        routeTemplate: "rpc/{controller}/{action}",
        defaults: new { action = "Get" }
    );
}

到目前为止,如果我点击浏览器:

  • [baseaddress]/locations/s0m3-gu1d-g0e5-hee5eeeee//有效
  • [baseaddress]/locations///找到多个结果
  • [baseaddress]/rpc/locations/dummy//有效

最奇怪的是,这曾经有效,直到我在执行一些更新时搞砸了我的 NuGet。我在这里缺少什么?

以 GET、POST、PUT 或 delete 开头的动词将自动映射到第一条路线,我的虚拟测试方法将通过 rpc 调用,这将落入第二条路线。

抛出的错误是带有消息的InvalidOperationException

Multiple actions were found that match the request: System.Linq.IQueryable`1[Myproject.Domain.Location] Get() on type Myproject.Webservices.Controllers.LocationsController System.Net.Http.HttpResponseMessage Dummy() on type Myproject.Webservices.Controllers.LocationsController

有什么想法吗?

最佳答案

问题在于路由的加载顺序。如果他们是这样的:

// A route that enables RPC requests
routes.MapHttpRoute(
    name: "RpcApi",
    routeTemplate: "rpc/{controller}/{action}",
    defaults: new { action = "Get" }
);

// Default route
routes.MapHttpRoute(
    name: "Default",
    routeTemplate: "{controller}/{id}",
   defaults: new { id =  RouteParameter.Optional }
);

它会很好地工作。首先,请求将映射到 RPC,然后是 Controller (它们可能有或没有 Id)。

关于c# - 找到与请求匹配的多个操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15115613/

相关文章:

c# - 是否有可用的 Office Web Apps Server Api?

asp.net-mvc - 在 IISExpress 上通过计算机名称访问 ASP.net Web api 时出现 400 错误请求

c# - 考虑使用 DataContractResolver 序列化错误

asp.net-mvc - 如何在 MVC3 中创建简单的路由?

c# - MongoDB 嵌入式多态对象

c# - 是否可以将正则表达式与 .net 中的二进制数据进行匹配?

C# 在新进程启动时引发事件

c# - 在不公开 ORM 模型的情况下使用 OData 进行查询?

c# - System.NullReferenceException 创建 viewModel

c# - 在不使用 OData 约定的情况下传递查询字符串参数?