2012-10-17 70 views
1

我已經創建了Web API服務。 我想要做的是從按鈕點擊後面的代碼中調用該API函數,即SaveSession(字符串數據),並以字符串格式傳遞整個表單集合數據作爲參數。 當我通過webclient.uploadstring(url,string)調用api的uri時; 它調用Web服務,但參數未通過。 請幫忙。從C#後面的代碼向WEB API函數發送數據#

+0

我建議檢查這方面的例子: 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 –

+0

它是從Jquery調用,我想從Code Behind –

+0

Can你發佈了一個Web API控制器方法的例子嗎?另外,您應該考慮使用HttpClient類來進行服務調用。它有一個PostAsync方法,它接受form-url-encoded數據作爲一組參數。 – Oppositional

回答

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); 
        } 
       } 
      } 
     } 
    } 
} 

我通常具有IsFormUrlEncodedContentReadAsFormUrlEncodedContentAsync方法作爲HttpContent擴展方法,但將它們放置在控制器爲了這個例子的目的。

相關問題