【问题标题】:Get verb is not calling to correct action获取动词没有要求采取正确的行动
【发布时间】:2019-12-16 13:37:20
【问题描述】:

我在同一个控制器中有两个 get 动词,所以我试图调用其中一个,但它调用了另一个。我想打电话给GetCoCDropdownOptionsAction,但它总是打电话给GetCoCCallLogHistory

我尝试重命名操作方法,发送 id 但它继续寻找第一个动词(具有 id 参数的那个)

//In the controller ABCController.cs
[HttpGet]
[ActionName("GetCoCCallLogHistory")]
public IHttpActionResult GetCoCCallLog(string code, int id)
{

[HttpGet]
[ActionName("GetCoCDropdownOptionsAction")]
public IHttpActionResult GetCoCDropdownOptions(string code)

//Routing
config.Routes.MapHttpRoute(
    name: "AllowingMultipleGetsId",
    routeTemplate: "api/{code}/{controller}/{action}/{id}",
    defaults: new { controller = "Home", id= RouteParameter.Optional },
    constraints: new { code= "[a-zA-Z]+(_[a-zA-Z]+)?" }
);

config.Routes.MapHttpRoute(
    name: "AllowingMultipleGets",
    routeTemplate: "api/{code}/{controller}/{action}",
    defaults: new { controller = "Home" },
    constraints: new { code = "[a-zA-Z]+(_[a-zA-Z]+)?" }
);

//In the javascript using angularjs
$http.get('/api/' + $scope.code + 
'/ABC/GetCoCDropdownOptionsAction').then(function (response) {
        //...
    }, function (response) {
        //...
    });

我收到此错误消息:

{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult GetCoCCallLog(System.String, Int32)' in 'xxx.ABCController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}

如果您需要更多信息,请提供任何帮助,让我知道。

【问题讨论】:

  • 尝试将int id 更改为int? id
  • 您是否打算将 id 设为可选?您已经说过它在路由配置中是可选的,但您通过将其设为 int 使其不是可选的。是哪个?
  • 我想调用 GetCoCDropdownOptionsAction 但它正在调用 GetCoCCallLogHistory
  • 根据服务器日志记录的请求 url 是什么?
  • 不确定你是不是这个意思:localhost:44331/api/xxx/ABC/GetCoCDropdownOptionsAction

标签: c# ajax rest asp.net-web-api


【解决方案1】:

我找到了解决方案,我上面还有另一条路线,所以它以前在看。

config.Routes.MapHttpRoute(
            name: "xsx",
            routeTemplate: "api/{code}/{controller}/{id}",
            defaults: new { controller = "Home", id = RouteParameter.Optional },
            constraints: new { marketCode = "[a-zA-Z]+(_[a-zA-Z]+)?" }
        );

我只是更改了顺序,问题就解决了,谢谢!

【讨论】:

    【解决方案2】:

    正如错误消息指出的那样,

    id 属于 System.Int32 即值类型正在获取 null 值,这是不可能的,int 的默认值为 0 并且 not null

    要使id 有可能成为null,您需要将其设置为nullable type

    为此更改此操作:-

    GetCoCCallLog(string code, int?id)

    【讨论】:

    • 我在尝试调用 GetCoCCallLog 时没有任何问题,问题是我在尝试调用 GetCoCDropdownOptionsAction,我做错了什么?我尝试了你的建议,现在没有错误,但我想调用其他方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多