我已經創建了Web API服務。 我想要做的是從按鈕點擊後面的代碼中調用該API函數,即SaveSession(字符串數據),並以字符串格式傳遞整個表單集合數據作爲參數。 當我通過webclient.uploadstring(url,string)調用api的uri時; 它調用Web服務,但參數未通過。 請幫忙。從C#後面的代碼向WEB API函數發送數據#
1
A
回答
3
不是使用接受字符串的控制器操作方法,而是可以讀取發佈到控制器的表單URL編碼內容。
在以下示例中,SessionController公開一個SaveSession()方法,該方法接受form-url編碼內容的POST,然後將會話數據作爲KeyValuePair實例的集合讀取。
示例客戶端構建鍵值對列表,然後使用HttpClient實例將FormUrlEncodedContent發佈到Web API控制器方法。
例SessionController:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace MvcApplication1.Controllers
{
public class SessionController : ApiController
{
/// <summary>
/// Saves specified the session data.
/// </summary>
/// <returns>
/// A <see cref="HttpResponseMessage"/> that represents the response to the requested operation.
/// </returns>
[HttpPost()]
public HttpResponseMessage SaveSession()
{
// Ensure content is form-url-encoded
if(!IsFormUrlEncodedContent(this.Request.Content))
{
return this.Request.CreateResponse(HttpStatusCode.BadRequest);
}
// Read content as a collection of key value pairs
foreach (var parameter in ReadAsFormUrlEncodedContentAsync(this.Request.Content).Result)
{
var key = parameter.Key;
var value = parameter.Value;
if(!String.IsNullOrEmpty(key))
{
// Do some work to persist session data here
}
}
return this.Request.CreateResponse(HttpStatusCode.OK);
}
/// <summary>
/// Determines whether the specified content is form URL encoded content.
/// </summary>
/// <param name="content">
/// The type that the <see cref="IsFormUrlEncodedContent(HttpContent)"/> method operates on.
/// </param>
/// <returns>
/// <see langword="true"/> if the specified content is form URL encoded content; otherwise, <see langword="false"/>.
/// </returns>
public static bool IsFormUrlEncodedContent(HttpContent content)
{
if (content == null || content.Headers == null)
{
return false;
}
return String.Equals(
content.Headers.ContentType.MediaType,
FormUrlEncodedMediaTypeFormatter.DefaultMediaType.MediaType,
StringComparison.OrdinalIgnoreCase
);
}
/// <summary>
/// Write the HTTP content to a collection of name/value pairs as an asynchronous operation.
/// </summary>
/// <param name="content">
/// The type that the <see cref="ReadAsFormUrlEncodedContentAsync(HttpContent)"/> method operates on.
/// </param>
/// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
/// <remarks>
/// The <see cref="ReadAsFormUrlEncodedContentAsync(HttpContent, CancellationToken)"/> method
/// uses the <see cref="Encoding.UTF8"/> format (or the character encoding of the document, if specified)
/// to parse the content. URL-encoded characters are decoded and multiple occurrences of the same form
/// parameter are listed as a single entry with a comma separating each value.
/// </remarks>
public static Task<IEnumerable<KeyValuePair<string, string>>> ReadAsFormUrlEncodedContentAsync(HttpContent content)
{
return ReadAsFormUrlEncodedContentAsync(content, CancellationToken.None);
}
/// <summary>
/// Write the HTTP content to a collection of name/value pairs as an asynchronous operation.
/// </summary>
/// <param name="content">
/// The type that the <see cref="ReadAsFormUrlEncodedContentAsync(HttpContent, CancellationToken)"/> method operates on.
/// </param>
/// <param name="cancellationToken">
/// The cancellation token used to propagate notification that the operation should be canceled.
/// </param>
/// <returns>The <see cref="Task"/> object representing the asynchronous operation.</returns>
/// <remarks>
/// The <see cref="ReadAsFormUrlEncodedContentAsync(HttpContent, CancellationToken)"/> method
/// uses the <see cref="Encoding.UTF8"/> format (or the character encoding of the document, if specified)
/// to parse the content. URL-encoded characters are decoded and multiple occurrences of the same form
/// parameter are listed as a single entry with a comma separating each value.
/// </remarks>
public static Task<IEnumerable<KeyValuePair<string, string>>> ReadAsFormUrlEncodedContentAsync(HttpContent content, CancellationToken cancellationToken)
{
return Task.Factory.StartNew<IEnumerable<KeyValuePair<string, string>>>(
(object state) =>
{
var result = new List<KeyValuePair<string, string>>();
var httpContent = state as HttpContent;
if (httpContent != null)
{
var encoding = Encoding.UTF8;
var charSet = httpContent.Headers.ContentType.CharSet;
if (!String.IsNullOrEmpty(charSet))
{
try
{
encoding = Encoding.GetEncoding(charSet);
}
catch (ArgumentException)
{
encoding = Encoding.UTF8;
}
}
NameValueCollection parameters = null;
using (var reader = new StreamReader(httpContent.ReadAsStreamAsync().Result, encoding))
{
parameters = HttpUtility.ParseQueryString(reader.ReadToEnd(), encoding);
}
if (parameters != null)
{
foreach(var key in parameters.AllKeys)
{
result.Add(
new KeyValuePair<string, string>(key, parameters[key])
);
}
}
}
return result;
},
content,
cancellationToken
);
}
}
}
實施例中調用客戶:
using System;
using System.Collections.Generic;
using System.Net.Http;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (var client = new HttpClient())
{
// Initialize HTTP client
client.BaseAddress = new Uri("http://localhost:26242/api/", UriKind.Absolute);
client.Timeout = TimeSpan.FromSeconds(10);
// Build session data to send
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("Item1", "Value1"));
values.Add(new KeyValuePair<string, string>("Item2", "Value2"));
values.Add(new KeyValuePair<string, string>("Item3", "Value3"));
// Send session data via POST using form-url-encoded content
using (var content = new FormUrlEncodedContent(values))
{
using (var response = client.PostAsync("session", content).Result)
{
Console.WriteLine(response.StatusCode);
}
}
}
}
}
}
我通常具有IsFormUrlEncodedContent和ReadAsFormUrlEncodedContentAsync方法作爲HttpContent擴展方法,但將它們放置在控制器爲了這個例子的目的。
相關問題
- 1. 從asp.net代碼發送數據背後的JavaScript函數
- 2. 寫在頁面加載從代碼JavaScript函數後面的C#
- 3. 如何發送數據在後面的代碼中的功能
- 4. 向Web Api發送列表或數組
- 5. 傳遞函數參數從c#代碼後面
- 6. 如何從java客戶端向c#web服務發送數據
- 7. 從C#web應用程序後面的代碼調用JavaScript函數
- 8. 發送一個JavaScript數組代碼後面(c#)使用AJAX
- 9. 在發送數據代碼
- 10. 無法從後面的c#代碼調用javascript函數
- 11. 如何從後面的c#代碼調用javascript函數
- 12. 從C#後面的代碼調用JS函數
- 13. 如何從後面的代碼調用jquery函數(document.ready函數)
- 14. 從JavaScript發送數據到第一次加載後的代碼
- 15. 在HTTP GET請求發送JSON數據從Java代碼REST API
- 16. 如何從C#代碼中的Response.Flush()後面的代碼調用JavaScript函數
- 17. 從Ajax函數調用代碼背後的c#函數
- 18. 從HTML/Javascript發送大字符串數據到後面的代碼
- 19. 嘗試從簡單的Python函數向C++發送參數
- 20. 從jquery中的C#文件後面的代碼獲取數據
- 21. 從C#調用C++函數並將數據發送回C#
- 22. 如何將表單數據「發送」到C#代碼,然後讓C#「發送」數據回來?
- 23. 從後面的代碼將數據發佈到其他網站
- 24. 如何從其他頁面向Javascript函數發送數組?
- 25. 從數學函數的C++代碼
- 26. 發送一個變量從我的ASP.NET頁面中的JavaScript腳本到代碼背後的C#函數
- 27. ASP.NET數據綁定雙向的,雙向的,從後面的代碼
- 28. 從後面的代碼SQL數據源/數據網格
- 29. 從代碼後面調用JavaScript函數的參數
- 30. 從C#中的Web Api獲取數據
我建議檢查這方面的例子: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api http://www.codeproject.com/Articles/344078/ASP-NET-WebAPI-Getting-Started-with-MVC4-and-WebAP –
它是從Jquery調用,我想從Code Behind –
Can你發佈了一個Web API控制器方法的例子嗎?另外,您應該考慮使用HttpClient類來進行服務調用。它有一個PostAsync方法,它接受form-url-encoded數據作爲一組參數。 – Oppositional