【问题标题】:I create a WebApi, but cant add it as web reference [duplicate]我创建了一个 Web Api,但无法将其添加为 Web 参考 [重复]
【发布时间】:2016-10-14 00:52:15
【问题描述】:

我正在关注这个tutorial。我创建了我的 WebApi 并在浏览器中正常工作。但是当尝试将它添加为网络参考时告诉我这个错误。

URL http://localhost/WebApi/api/test 处的文档未被识别为已知文档类型。 来自每种已知类型的错误消息可能会帮助您解决问题: - 来自“XML Schema”的报告是“根级别的数据无效。第 1 行,位置 1。'。 - 来自“DISCO 文档”的报告是“数据”

测试控制器

namespace WebApi.Controllers
{
    public class TestController : ApiController
    {
        public HttpResponseMessage Get()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("GET: Test message")
            };
        }

        public HttpResponseMessage Post()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("POST: Test message")
            };
        }

        public HttpResponseMessage Put()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("PUT: Test message")
            };
        }
    }
}

浏览器正常,但显示错误。

【问题讨论】:

标签: c# asp.net visual-studio asp.net-web-api


【解决方案1】:

除了链接中的答案。您可以通过多种方式访问​​ WebAPI 控制器。

  1. 您可以使用 Javascript、Ajax、AngularJs 等从客户端访问。
  2. 任何可以发出 Http 请求的框架,例如,如果您想在任何 .Net 应用程序上安装 ASP.Net WebAPI 客户端。 (控制台、WindowsForm 等)然后在实例化 HttpClient() 之前添加引用。 请参阅下面的示例代码

        var client =new HttpClient(); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); 
    var result = client.GetAsync(new Uri("http://localhost:16665/api/myApiControllerName")).Result; 
    

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多