MVC 4网页API发布 [英] MVC 4 Web Api Post

查看:236
本文介绍了MVC 4网页API发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打从遥远的客户端,我需要通过HTTP发送数据的插入。结果
我可以使用 getPerformances()正确与的HttpClient API /表演?日期= { 0}

我想问一下,如果我的 postPorformances()里面implemntation我的 PerformancesController 是corrrect,如果它是如何从客户端调用它?

下面是我的实现:

 公共类PerformancesController:ApiController
    {
        //获取API /表演
        公共IEnumerable的<性能与GT; getPerformances(DateTime的日期)
        {
            返回DataProvider.Instance.getPerformances(日期);
        }        公众的Htt presponseMessage postPerformances(性能P)
        {
            DataProvider.Instance.insertPerformance(P);
            VAR响应= Request.CreateResponse<性能与GT;(的HTTPStatus code.Created,P);
            返回响应;
        }
    }

 公共类性能{
    公众诠释标识{获取;设置;}
    公众的DateTime日期{获取;设置;}
    公共十进制值{获得;设置;}
}

我已经试过这一个,但我确信注:

私人只读的HttpClient _client;
  串请求=的String.Format(API /表演);
  VAR jsonString ={\\日期\\:+ p.Date +,\\价值\\:+ p.Value +};
  VAR httpContent =新的StringContent(jsonString,Encoding.UTF8,应用/ JSON);
  VAR消息=等待_client.PutAsync(请求,httpContent);


解决方案

您可以使用的HttpClient 来调用这个方法:

 使用(VAR的客户=新的HttpClient())
{
    client.BaseAddress =新的URI(http://example.com);
    VAR的结果= client.PostAsync(/ API /表演,新
    {
        ID = 1,
        日期= DateTime.Now,
        值= 1.5
    },新JsonMediaTypeFormatter())结果。
    如果(result.IsSuccessStatus code)
    {
        Console.writeLine(性能的实例成功发送到API);
    }
    其他
    {
        字符串内容= result.Content.ReadAsStringAsync()结果。
        Console.WriteLine(哎呀,发生了错误,这里的原始响应:{0},内容);
    }
}

在这个例子中,我使用普通的 PostAsync< T> 办法让我送任何对象作为第二个参数,然后选择媒体类型格式。在这里,我用一个匿名对象模仿相同的结构,你的性能模式的服务器和 JsonMediaTypeFormatter 上。你当然可以共享这个性能客户端,并把它放在一个合同项目的服务器之间的模式,使服务器上的改变也将自动在客户端上反映出来。

边注:C#的命名习惯上还是会把方法名应该以大写字母开头。因此, getPerformances GetPerformances 甚至更好获取 postPerformances PostPerformances 甚至更好发表

I want to make an insertion from a distant client for that I need to send data via http.
I can use the getPerformances() correctly with an httpClient api/performances?date={0}

I want to ask if my postPorformances() implemntation inside my PerformancesController is corrrect and if it is how to call it from a client?

Here is my implementation:

public class PerformancesController : ApiController
    {
        // GET api/performances
        public IEnumerable<Performance> getPerformances(DateTime date)
        {
            return DataProvider.Instance.getPerformances(date);
        }

        public HttpResponseMessage postPerformances(Performance p)
        {
            DataProvider.Instance.insertPerformance(p);
            var response = Request.CreateResponse<Performance>(HttpStatusCode.Created, p);
            return response;
        }
    }

public class Performance {
    public int Id {get;set;}
    public DateTime Date {get;set;}
    public decimal Value {get;set;}
}

I have tried this one but I'm note sure:

  private readonly HttpClient _client;
  string request = String.Format("api/performances");
  var jsonString = "{\"Date\":" + p.Date + ",\"Value\":" + p.Value + "}";
  var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
  var message = await _client.PutAsync(request, httpContent);

解决方案

You could use the HttpClient to call this method:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://example.com");
    var result = client.PostAsync("/api/performances", new
    {
        id = 1,
        date = DateTime.Now,
        value = 1.5
    }, new JsonMediaTypeFormatter()).Result;
    if (result.IsSuccessStatusCode)
    {
        Console.writeLine("Performance instance successfully sent to the API");
    }
    else
    {
        string content = result.Content.ReadAsStringAsync().Result;
        Console.WriteLine("oops, an error occurred, here's the raw response: {0}", content);
    }
}

In this example I am using the generic PostAsync<T> method allowing me to send any object as second parameter and choose the media type formatter. Here I have used an anonymous object mimicking the same structure as your Performance model on the server and the JsonMediaTypeFormatter. You could of course share this Performance model between the client and the server by placing it in a contracts project so that changes on the server would also be automatically reflected on the client.

Side remark: C# naming convention dictates that method names should start with a capital letter. So getPerformances should be GetPerformances or even better Get and postPerformances should be PostPerformances or even better Post.

这篇关于MVC 4网页API发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆