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

标签 .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 的“包装”类,它处理 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};
}

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

最佳答案

首先,检查App_Start下的WebApiConfig.cs是否具有像这样映射的路由(这是默认的)。

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出来。

顺便说一句,约定是使用复数形式作为 Controller 类名。因此,您的 Controller 可以命名为 CustomerDetailsController 甚至更好的 CustomersController,因为细节是您处理的内容。

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

关于.net - ASP.NET Web API - 来自 ASP.NET MVC 4 应用程序的 POST/PUT/DELETE 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17355501/

相关文章:

c++ - 实现 Bind()(LINQ 中的 SelectMany)而不产生 yield (在 C++ 中)

asp.net-mvc - 写入/输出未转义的 HTML 字符串

c# - 把一些 parent 的 child 某项属性(property)等于某项值(value)的记录退回去?

java - 微服务架构,在这种情况下什么是服务

javascript - 为什么 Meteor.call() 无法识别?

c# - 为什么通用类型定义实现的接口(interface)会丢失类型信息?

c# - 如何获取当前帧?

c# - LINQ vs sql - 带回太多行

REST Servlet 正在开发中,但在远程 Tomcat 上