asp.net webapi 2问题HTTP帖子和参数

时间:2015-05-17 15:57:16

标签: asp.net asp.net-web-api

我正在努力让这个工作,但浪费了2天仍然没有运气。 我应该承认我不是一个经验丰富的程序员,我是初学者并且学习ASP.NET WebApi 2

我从模板创建了一个WebApi2,并且get方法有效,但无法使HTTP帖子生效。有人可以帮忙吗?

这是控制器

namespace WebApplication1.Controllers
{
    public class CustomersController : ApiController
    {
        Customer[] customers = new Customer[]
        {
            new Customer { CustName="Arvind", CustPhone="4024567892", ID=1},
            new Customer {CustName="Mike",CustPhone="4021231234", ID=2 }
        };

        public IEnumerable<Customer> GetAllCustomers()
        {
            return customers;
        }

        public IHttpActionResult GetCustomer(int ID)
        {
            var customer = customers.FirstOrDefault((p) => p.ID == ID);
            if (customer==null)
            {
                return NotFound();
            }
            return Ok(customer);
        }
        [HttpPost]
        [ActionName("PostCustomer")]
        public IHttpActionResult PostCustomer([FromBody]int ID)
        {
            var customer = customers.FirstOrDefault((p) => p.ID == ID);

            if (customer == null)
            {
                return NotFound();
            }
            return Ok(customer);
        }

    }
}

这是HTML帖子

<div>
    <h2>All Customers</h2>
    <ul id="customers" />
</div>
<div>
    <h2>Search by ID</h2>
    <input type="text" id="ID" size="5" />
    <input type="button" value="Search" onclick="find();" />
    <p id="customer" />
</div>
<form method="post" action="api/customers/PostCustomer">
<div>
    <h2>Search by ID</h2>
    <input type="text" id="ID" size="5" />
    <input type="submit" value="Search"  />

</div>
    </form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/customers';

$(document).ready(function () {
  // Send an AJAX request
  $.getJSON(uri)
      .done(function (data) {
        // On success, 'data' contains a list of products.
        $.each(data, function (key, item) {
          // Add a list item for the product.
          $('<li>', { text: formatItem(item) }).appendTo($('#customers'));
        });
      });
});

function formatItem(item) {
  return item.CustName + ': ' + item.ID;
}

function find() {
  var id = $('#ID').val();
  $.getJSON(uri + '/' + id)
      .done(function (data) {
        $('#customer').text(formatItem(data));
      })
      .fail(function (jqXHR, textStatus, err) {
        $('#customer').text('Error: ' + err);
      });
}
</script>

最后是webconfig文件

namespace WebApplication1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

3 个答案:

答案 0 :(得分:0)

我认为您需要为输入设置名称

&#13;
&#13;
<input type="text" id="ID" size="5" />
&#13;
&#13;
&#13;

&#13;
&#13;
<input type="text" id="ID" name="ID" size="5" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

首先定义参数:对于<form>标记中的帖子数据,首先需要在输入中定义参数名称,如下所示:

<input type="text" id="ID" name="ID" size="5" />

然后发送帖子请求:发送帖子请求,因此您应该将js中的$.getJSON更改为$.postJSON

最后我建议您使用Postman,Postman是一个非常棒的REST API测试客户端,可以帮助您更轻松地开发Web API应用程序。

答案 2 :(得分:0)

当前代码

的错误很少
  1. 使用HTML,你只能通过名字参数发送输入字段,ID在这里没有任何意义
  2. 您正在将数据发送到/ api / customers / PostCustomer,而这是一个让我们说通常的方式在MVC中您的路由被定义为routeTemplate:“api / {controller} / {id}”,这意味着在/ api / customers WebAPI正在根据请求协商使用什么方法(GET,POST,PUT ......)。我个人并不喜欢这个,但这是最简单的启动方式,如果你想要更多的MVC方法,默认路由应该是routeTemplate:“api / {controller} / {action} / {id}”那样你的当前网址将有效。更多关于http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
  3. 我建议您使用一些REST插件为您的浏览器测试API,因为您可以更轻松地查明错误。

    另外,建议不要将参数直接发送到您的方法,您应该预先验证它们,请参阅http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

    学习好运;) 以下是启动http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api

    的良好链接