WebApi 2 POST方法与单个字符串参数无法正常工作

12 浏览
0 Comments

WebApi 2 POST方法与单个字符串参数无法正常工作

我有以下控制器:

public class ValuesController : ApiController
{
    // POST api/values
    public IHttpActionResult Post(string filterName)
    {
        return new JsonResult(filterName, new JsonSerializerSettings(), Encoding.UTF8, this);
    }
}

WebApi配置:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional });

我使用以下JS代码调用API:

$.ajax(
{
    url: "/api/values/",
    type: "POST",
    dataType: 'json',
    data: { filterName: "Dirty Deeds" },
    success: function (result) {
        console.log(result);
    },
    error: function (xhr, status, p3, p4) {
        var err = "Error " + " " + status + " " + p3;
        if (xhr.responseText && xhr.responseText[0] == "{")
            err = JSON.parse(xhr.responseText).message;
        console.log(err);
    }
});

我得到了405方法不允许(post)。

0