2

我有一个 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 的“包装器”类,它处理 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};
}

我已经尝试在谷歌上搜索了几个小时,如果有人能指出我正确的方向,我将不胜感激。

4

1 回答 1

3

首先,检查WebApiConfig.csunderApp_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);

有关更多信息,请查看内容。

顺便说一句,约定是使用复数作为控制器类名称。因此,您的控制器可以命名为 CustomerDetailsController 甚至更好的 CustomersController,因为您处理的是细节。

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

于 2013-06-28T03:55:48.217 回答