【发布时间】:2017-09-22 19:03:24
【问题描述】:
必须使用 Web API。控制器如下所示:
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
消息 - 方法不允许
【问题讨论】:
-
Stack Overflow不是免费的代码编写服务。您应该尝试自己编写代码。在doing more research 之后,如果您有问题,您可以发布您尝试过的内容,并清楚地解释什么不起作用,并提供一个minimal reproducible example 。我建议阅读How to Ask 一个好问题和the perfect question。另外,请务必使用tour。
-
您使用 HttpClient 加载与方法关联的路由。你试过什么?
-
试试这样:HttpClient client = new HttpClient(); client.BaseAddress = new Uri("localhost:49319/"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.GetAsync("api/local/product/{productId}/ export").Result; 对我来说很清楚我不能使用 Get 但我应该使用什么?
-
是什么让你觉得你不能使用Get? (PS-您应该编辑您的问题以添加不起作用的相关代码以及您收到的任何错误)
-
使用上面的代码我得到:错误代码 MethodNotAllowed:消息 - 方法不允许