使用http.get - ASP.NET MVC将字符串发送到服务器控制器

时间:2016-10-01 15:58:59

标签: angularjs asp.net-mvc

我是mvc的新手,我想发送带参数的get请求,但服务器端的参数始终为null。 在客户端,我使用js文件中的angular执行以下请求:

$http.get('api/person/getPersons', "TEST");

我的PersonController有以下方法:

    /// <summary>
    /// Get all persons from the database.
    /// </summary>
    /// <returns>All persons.</returns>
    [HttpGet]
    [ActionName("getPersons")]
    public IHttpActionResult GetPersons(string personToFind)
    {
        return this.Content(HttpStatusCode.OK, personToFind);
    }

在这种情况下,字符串保持为null,也尝试了以下两个选项,但它们都没有工作。

    /// <summary>
    /// Get all persons from the database.
    /// </summary>
    /// <returns>All persons.</returns>
    [HttpGet]
    [ActionName("getPersons")]
    public IHttpActionResult GetPersons([FromBody] string personToFind)
    {
        return this.Content(HttpStatusCode.OK, personToFind);
    }

    /// <summary>
    /// Get all persons from the database.
    /// </summary>
    /// <returns>All persons.</returns>
    [HttpGet]
    [ActionName("getPersons")]
    public IHttpActionResult GetPersons([FromUri] string personToFind)
    {
        return this.Content(HttpStatusCode.OK, personToFind);
    }

我还试图从“人物”中找到一个物体。但这给了我一个空的System.object。

如果有人知道我做错了什么,我会很高兴。

1 个答案:

答案 0 :(得分:0)

尝试使用$http.get('api/person/getPersons?personToFind=TEST")类型的[FromUri]

如果搜索字词包含特殊字符,则

$http.get('api/person/getPersons?personToFind=' + encodeURIComponent("TEST"))处于更安全的一面。