使用ASP.NET WebAPI

时间:2017-09-22 19:03:24

标签: c# asp.net

必须使用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

消息 - 不允许的方法

2 个答案:

答案 0 :(得分: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();

                }
            }
        }

答案 1 :(得分:0)

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

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