javascript - 带有单个字符串参数的 WebApi 2 POST 不起作用

标签 javascript c# asp.net-web-api asp.net-web-api2

我有以下 Controller :

public class ValuesController : ApiController
{
    // POST api/values
    public IHttpActionResult Post(string filterName)
    {
        return new JsonResult<string>(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)

最佳答案

c#

public class ValuesController : ApiController
{
    // POST api/values
    [HttpPost] // added attribute
    public IHttpActionResult Post([FromBody] string filterName) // added FromBody as this is how you are sending the data
    {
        return new JsonResult<string>(filterName, new JsonSerializerSettings(), Encoding.UTF8, this);
    }

JavaScript

$.ajax(
{
    url: "/api/Values/", // be consistent and case the route the same as the ApiController
    type: "POST",
    dataType: 'json',
    data: "=Dirty Deeds", // add an = sign
    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);
    }
});

说明

因为您只发送一个值,所以在它前面添加 = 符号,这样它将被视为表单编码。如果您想清楚地表明这是您对 ajax 调用所做的,您还可以添加内容类型。

contentType: 'application/x-www-form-urlencoded'

或者,您也可以通过 URL 发送内容,或者将内容包装在服务器上的对象以及 ajax 调用中,然后将其字符串化。

public class Filter {
    public string FilterName {get;set;}
}

public class ValuesController : ApiController
{
    // POST api/values
    [HttpPost] // added attribute
    public IHttpActionResult Post([FromBody] Filter filter) // added FromBody as this is how you are sending the data
    {
        return new JsonResult<string>(filter.FilterName, new JsonSerializerSettings(), Encoding.UTF8, this);
    }

JavaScript

$.ajax(
{
    url: "/api/Values/", // be consistent and case the route the same as the ApiController
    type: "POST",
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify({FilterName: "Dirty Deeds"}), // send as json
    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);
    }
});

关于javascript - 带有单个字符串参数的 WebApi 2 POST 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37842231/

相关文章:

javascript - 单击 div 内的 iFrame 时如何切换项目?

javascript - 如何通过单击另一个 iframe 的链接在 iframe 中加载网页

c# - 如何访问 MemoryStream 中的特定字节组?

c# - 编辑 csproj 文件中的 DefineConstants

c# - 在 linq 中返回所有具有相同名称的 xml 项

javascript - 图像选择器不止一个

azure - OWIN静态文件安全

asp.net-web-api - 防止 WebAPI OData Controller 名称冲突?

c# - 在 web api 中使用多个自定义操作路由配置

javascript - 我需要angularjs中没有数组括号的输出值