2017-09-22 136 views
-3

必須使用Web API。控制器看起來像這樣:使用ASP.NET WebAPI

using System; 
using System.Collections.Generic; 
using System.Web.Http; 
using ERPService.Api.Models; 
using ERPService.Core.Services; 

namespace ERPService.Api.Controllers 
{ 

    [RoutePrefix("api/local")] 
    public class LocalProductController : BaseApiController 
    { 
     [Route("product/{productId}/export")] 
     public ApiResponse<IList<ServiceResponse<object>>> ExportProduct(int productId) 
     { 
      return Response(this.ServiceFactory.ProductService.ExportProduct(productId)); 
     } 

    } 
} 

使用HttpClient如何調用ExportProduct函數? 我創建了一個控制檯應用程序來消費這樣的:

HttpClient client = new HttpClient(); 
client.BaseAddress = new Uri("http://localhost:49319/"); 
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

HttpResponseMessage response = client.GetAsync("api/local/product/{productId}/export").Result; 

結果是錯誤如下:

錯誤代碼 - MethodNotAllowed

消息 - 不允許的方法

+2

[so] is * not * a free code writing service。預計你會嘗試**自己編寫代碼**。在[做更多研究]之後(http://meta.stackoverflow.com/questions/261592),如果你有問題,你可以**發佈你已經嘗試過**的清單,說明什麼是不工作的**並提供** [mcve] **。我建議閱讀[問]一個好問題和[完美問題](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/)。另外,一定要參加[旅遊]。 – Igor

+0

您使用HttpClient加載與該方法關聯的路由。你有什麼嘗試? – squillman

+0

嘗試像這樣: HttpClient client = new HttpClient(); client.BaseAddress = new Uri(「http:// localhost:49319 /」); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(「application/json」)); HttpResponseMessage response = client.GetAsync(「api/local/product/{productId}/export」)。 很明顯,我無法使用Get,但應該使用什麼? – BenjiK

回答

0
string json; 
     WebRequest req = HttpWebRequest.Create(url); 
     req.Method = "GET"; 
     using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) 
     { 
      using (Stream responseStream = response.GetResponseStream()) 
      { 
       using (StreamReader responseReader = new StreamReader(responseStream)) 
       { 

        json = responseReader.ReadToEnd(); 

       } 
      } 
     } 
0

實測值該問題的解決方案:必須添加[HttpGet]屬性,使其看起來像這樣:

[Route("product/{productId}/export")] 
[HttpGet] 
public ApiResponse<IList<ServiceResponse<object>>> ExportProduct(int productId) 
{ 
    return Response(this.ServiceFactory.ProductService.ExportProduct(productId)); 
}