如何通过FromBody将DataTable传递给Web API POST方法(C#)

时间:2016-01-06 05:50:10

标签: c# winforms asp.net-web-api frombodyattribute

我从Winforms客户端成功调用Web API应用程序中的POST方法,该客户端传递了存储过程的一些参数。

我希望尽可能通过FromBody功能将存储过程的结果(我必须首先在客户端上运行)传递给POST方法。

要通过网络发送大量数据,但我现在的方式是运行SP两次 - 首先在客户端Winforms应用程序上运行,然后在Web API服务器应用程序上运行SP并且同时调用此SP似乎有时会导致一些问题。

所以,如果可行的话,我想通过" FromBody"发送DataTable。或者,如果可取的话,是数据的XML化或jsonized版本(然后在另一端解压缩,在调用相应的GET方法时将其转换为html进行检索。

是否有人有任何可以显示的代码?

我可以看到刚刚通过参数的现有代码here

更新

好的,根据Amit Kumar Ghosh的回答,我将代码更改为:

WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new    
HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();

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


    config.Formatters.Add(new DataTableMediaTypeFormatter());
}

public class DataTableMediaTypeFormatter : BufferedMediaTypeFormatter
{
    public DataTableMediaTypeFormatter()
        : base()
    {
        SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("test/dt"));
    }

    public override object ReadFromStream(Type type, Stream readStream,
        HttpContent content, IFormatterLogger formatterLogger, System.Threading.CancellationToken cancellationToken)
    {
        var data = new StreamReader(readStream).ReadToEnd();
        var obj = JsonConvert.DeserializeObject<DataTable>(data);
        return obj;
    }

    public override bool CanReadType(Type type)
    {
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        return true;
    }
}

CONTROLLER

[Route("{unit}/{begindate}/{enddate}/{stringifiedjsondata}")]
[HttpPost]
public void Post(string unit, string begindate, string enddate, DataTable stringifiedjsondata)
{
    DataTable dt = stringifiedjsondata;
    . . .

客户端

private async Task SaveProduceUsageFileOnServer(string beginMonth, string beginYear, string endMonth, string endYear)
{
    string beginRange = String.Format("{0}{1}", beginYear, beginMonth);
    string endRange = String.Format("{0}{1}", endYear, endMonth);
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:52194");
    string dataAsJson = JsonConvert.SerializeObject(_rawAndCalcdDataAmalgamatedList, Formatting.Indented);
    String uriToCall = String.Format("/api/produceusage/{0}/{1}/{2}/{3}", _unit, beginRange, endRange, @dataAsJson);
    HttpResponseMessage response = await client.PostAsync(uriToCall, null);
}

......但仍未达到控制器;特别是,&#34; DataTable中的断点dt = dtPassedAsJson;&#34;永远不会到达。

实际上,令我惊讶的是它没有崩溃,因为传递了一个字符串,但那里声明的数据类型是&#34; DataTable&#34;

更新2

在我意识到它不是我从客户端传递的字符串/ jsonized DataTable之后,我也尝试了这个,但是字符串化/ jsonized通用列表:

WEB API CONTROLLER

[Route("{unit}/{begindate}/{enddate}/{stringifiedjsondata}")]
[HttpPost]
public void Post(string unit, string begindate, string enddate, List<ProduceUsage> stringifiedjsondata)
{
    List<ProduceUsage> _produceUsageList = stringifiedjsondata;

WebApiConfig.cs

我将其添加到Register方法:

config.Formatters.Add(new GenericProduceUsageListMediaTypeFormatter());

......还有这个新课程:

// adapted from DataTableMediaTypeFormatter above
public class GenericProduceUsageListMediaTypeFormatter : BufferedMediaTypeFormatter
{
    public GenericProduceUsageListMediaTypeFormatter()
        : base()
    {
        SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("test/dt"));
    }

    public override object ReadFromStream(Type type, Stream readStream,
        HttpContent content, IFormatterLogger formatterLogger, System.Threading.CancellationToken cancellationToken)
    {
        var data = new StreamReader(readStream).ReadToEnd();
        var obj = JsonConvert.DeserializeObject<List<ProduceUsage>>(data);
        return obj;
    }

    public override bool CanReadType(Type type)
    {
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        return true;
    }
}

尽管如此,控制器中的主要断点线:

List<ProduceUsage> _produceUsageList = stringifiedjsondata;

...未到达。

4 个答案:

答案 0 :(得分:1)

或jsonized版本的数据(然后在另一端解压缩

我结束了这个 -

public class ParentController : ApiController
{
    public string Post(DataTable id)
    {
        return "hello world";
    }
}
配置

中的

config.Formatters.Add(new DataTableMediaTypeFormatter());

和 -

public class DataTableMediaTypeFormatter : BufferedMediaTypeFormatter
{
    public DataTableMediaTypeFormatter()
        : base()
    {
        SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("test/dt"));
    }

    public override object ReadFromStream(Type type, System.IO.Stream readStream,
        System.Net.Http.HttpContent content, IFormatterLogger formatterLogger, System.Threading.CancellationToken cancellationToken)
    {
        var data = new StreamReader(readStream).ReadToEnd();
        var obj = JsonConvert.DeserializeObject<DataTable>(data);
        return obj;
    }

    public override bool CanReadType(Type type)
    {
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        return true;
    }
}

header of my request -
User-Agent: Fiddler
Host: localhost:60957
Content-Type : test/dt
Content-Length: 28

身体 -

[{"Name":"Amit","Age":"27"}]

答案 1 :(得分:1)

我之前已经做过一次,虽然代码现在已被取代,所以我只能从我的TFS历史记录中获得点点滴滴。

从我的控制台应用程序,我会发布数据(是我转换为POCO的DataTable),如下所示;

            using (HttpClient httpClient = new HttpClient())
            {
                MyDataType data = BogusMethodToPopulateData();

                httpClient.BaseAddress = new Uri(Properties.Settings.Default.MyService);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response;

                // Add reference to System.Net.Http.Formatting.dll
                response = await httpClient.PostAsJsonAsync("api/revise", data);

                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("File generation process completed successfully.");
                }
            }

在服务器端,我有以下内容。这里的概念主要基于链接帖子的Sending Complex Types部分。我知道你特意看的是DataTables,但我确信你可以搞乱这些例子或将你的数据提取到POCO中;

    // https://damienbod.wordpress.com/2014/08/22/web-api-2-exploring-parameter-binding/
    // http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-1
    // http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
    [POST("revise")]
    public IEnumerable<Revised_Data> Revise(MyDataType data)
    {
        if (ModelState.IsValid && data != null)
        {
            return ProcessData(data.year, data.period, data.DataToProcess).AsEnumerable();
        }
        return null;
    }

答案 2 :(得分:1)

客户端实际上是以json的形式传递数据表,然后根据特殊媒体类型webapi运行时将json再次转换为服务器上的数据表。

答案 3 :(得分:0)

见Hernan Guzman的回答here

基本上,你必须在服务器上的方法中添加“[FromBody]”,然后从客户端传递数据,在URL参数之后添加它。