ASP.NET Web API - 来自ASP.NET MVC 4应用程序的POST / PUT / DELETE请求

时间:2013-06-28 00:42:01

标签: .net asp.net-mvc rest asp.net-mvc-4 asp.net-web-api

我有一个ASP.NET Web API REST,用于处理来自ASP.NET MVC 4应用程序的数据请求

namespace CandidateAPI.Controllers
{
  public class CustomerDetailController : ApiController
  {

    private static readonly CustomerDetailRepository Repository = new CustomerDetailRepository();

    public IEnumerable<CustomerDetail> GetAllCustomerDetails()
    {
        return Repository.GetAll();
    }

    public CustomerDetail GetCustomerDetailById(int id)
    {
        return Repository.Get(id);
    }


    public HttpResponseMessage PostCustomerDetail(CustomerDetail item)
    {
        item = Repository.Add(item);
        var response = Request.CreateResponse<CustomerDetail>(HttpStatusCode.Created, item);

        var uri = Url.Link("DefaultApi", new { id = item.ID });
        if (uri != null) response.Headers.Location = new Uri(uri);
        return response;
    }
  }

}

现在在ASP.NET MVC4应用程序中,我有一个调用所述WEB API的'wrapper'类,它处理GET请求

 public class CustomerDetailsService : BaseService, ICustomerDetailsService
 {
    private readonly string api = BaseUri + "/customerdetail";

    public CustomerDetail GetCustomerDetails(int id) {

        string uri = api + "/getcustomerdetailbyid?id=" + id;

        using (var httpClient = new HttpClient())
        {
            Task<String> response = httpClient.GetStringAsync(uri);
            return JsonConvert.DeserializeObjectAsync<CustomerDetail>(response.Result).Result;
        }
    }
}

现在,我的问题是POST / PUT / DELETE REST请求

 public class CustomerDetailsService : BaseService, ICustomerDetailsService
 {
    private readonly string api = BaseUri + "/customerdetail";

    // GET -- works perfect
    public CustomerDetail GetCustomerDetails(int id) {

        string uri = api + "/getcustomerdetailbyid?id=" + id;

        using (var httpClient = new HttpClient())
        {
            Task<String> response = httpClient.GetStringAsync(uri);
            return JsonConvert.DeserializeObjectAsync<CustomerDetail>(response.Result).Result;
        }
    }

    //PUT
    public void Add(CustomerDetail detail) { //need code here };

    //POST
    public void Save(CustomerDetail detail) { //need code here };

    //DELETE
    public void Delete(int id) { //need code here};
}

我已经尝试使用谷歌搜索了几个小时,如果有人能指出我正确的方向,我会非常感激。

1 个答案:

答案 0 :(得分:3)

首先,检查WebApiConfig.cs下的App_Start是否有如此映射的路由(这是默认设置)。

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

通过这种方式,路由基于HTTP方法发生。因此,如果您向/ api / CustomerDetail / 123发出GET,则会调用您的操作方法GetCustomerDetailById(int)。 GET到/ api / CustomerDetail将致电GetAllCustomerDetails()。尽管可以这样做,但您不需要在URI中使用操作方法名称。

对于GET,这将有效。

Task<String> response = httpClient.GetStringAsync
        ("http://localhost:<port>/api/CustomerDetail/123");

对于POST,这将有效。

HttpClient client = new HttpClient();
var task = client.PostAsJsonAsync<CustomerDetail>
             ("http://localhost:<port>/api/CustomerDetail",
                     new CustomerDetail() { // Set properties });

您也可以使用

var detail = new CustomerDetail() { // Set properties };
HttpContent content = new ObjectContent<CustomerDetail>(
                           detail, new JsonMediaTypeFormatter());
var task = client.PostAsync("api/CustomerDetail", content);

有关详情,请查看this

BTW,惯例是使用复数作为控制器类名。因此,您的控制器可以命名为CustomerDetailsController,甚至更好的CustomerController,因为细节是您处理的。

此外,POST通常用于创建资源和PUT以更新资源。