【问题标题】:Consume ASP.NET WebAPI使用 ASP.NET WebAPI
【发布时间】: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:消息 - 方法不允许

标签: c# asp.net


【解决方案1】:
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();

                }
            }
        }

【讨论】:

    【解决方案2】:

    找到问题的解决方案:必须添加 [HttpGet] 属性,所以它应该如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      • 2012-07-10
      • 2013-11-06
      • 1970-01-01
      • 2017-11-02
      • 2017-04-04
      相关资源
      最近更新 更多