调用了错误的$http Get方法

本文关键字:http Get 方法 错误 调用 | 更新日期: 2023-09-27 18:29:40

我正在尝试使用$http.get方法来检索记录。调用的不是接受被调用参数的Get方法,而是空的Get方法。有人能告诉我我做错了什么,以及如何修复它,以便调用正确的Get方法吗?

注册控制器

// Empty method that gets hit
public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    return response;
}
// How do I structure my $http.get to have this method called?
public HttpResponseMessage Get(int pilotId)
{
    PilotModel pilot = this.RetrievePilot(pilotId);
    var response = new HttpResponseMessage();
    // If returnValue is null, the email or password was incorrect.
    if (pilot != null)
    {
        response = Request.CreateResponse<PilotModel>(HttpStatusCode.Created, pilot);
    }
    else
    {
        response = Request.CreateResponse<PilotModel>(HttpStatusCode.BadRequest, pilot);
    }
    return response;
}

前端(删除额外代码不需要显示问题…我相信)

var app = angular.module('MyRegistrationApp', []);
app.controller('RegistrationController', function ($scope, $http) {
    initializeVariables();
    var loggedInUser = JSON.parse(window.sessionStorage.getItem('LoggedInUser'));
    if (loggedInUser !== null && loggedInUser.PilotId > 0) {
        // Shouldn't this url cause the Get with parametes to be called?
        var url = 'api/registration/' + loggedInUser.PilotId;
        $(document).ready(function () {
            $http({
                method: 'GET',
                url: url,
            }).then(function successCallback(response) {
                initializeVariables(response);
            }, function errorCallback(response) {
                alert(response.statusText);
            });
        });
    }
});

调用了错误的$http Get方法

您的问题是您打算对此进行GET调用

http://my-api-url/api/registration/1

但事实上,你的控制器正在期待这个:

http://my-api-url/api/registration?pilotId=1

只要尝试将url变量更改为下面的示例,您就会看到它执行了正确的操作。

var url = 'api/registration?pilotId=' + loggedInUser.PilotId;

之所以会发生这种情况,是因为在GET请求中,参数是作为查询字符串发送的。如果您对此满意,只需将url更改为上面的代码即可。如果没有,那么需要对API进行一些调整,但不要害怕。

注册控制器:

[RoutePrefix("api")]
public class RegistrationController : ApiController
{
    [Route("registration")]
    public HttpResponseMessage Get()
    {
        var response = new HttpResponseMessage();
        return response;
    }
    [Route("registration/{pilotId:int}")]
    public HttpResponseMessage Get(int pilotId)
    {
        var response = new HttpResponseMessage();
        //Your code goes here...
        return response;
    }
}

在RegistrationController中进行这些修改后,您现有的代码将按预期工作。基本上,所有的"魔力"都是Route属性,它为您提供了对API中URL的更多控制。

此特定路线:

[Route("registration/{pilotId:int}")]

正在创建一个URL,该URL由"api/{controller}/"和在约束{pilotId:int}中定义的类型为int的参数组成。有了这个约束,我们强制要求在"注册"之后传递的参数必须是int。

我鼓励您查看本教程中的"属性路由",它非常有用。