简体   繁体   English

在类库中使用Web API

[英]Consuming Web API in Class library

I'm building plugin in auto-cad and using class library and web API with entity framework But every time i try to consume web API in my class library the response returns with "Not Found". 我在auto-cad中构建插件,并使用带有实体框架的类库和Web API,但是每次我尝试在类库中使用Web API时,响应都会返回“未找到”。 This is my code of class library 这是我的类库代码

[CommandMethod("Doit")]
      public void Test()
    {
        Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

        Checker c = new Checker() { WholeArea = 1000, BuildingArea = 200, Status = 1 };

        using (var client = new HttpClient())
        {
            client.BaseAddress =new  Uri("http://localhost:52133/api");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = client.PostAsJsonAsync("Checker", c).Result;
            if (response.IsSuccessStatusCode)
            {
                ed.WriteMessage("Hello data");
            }
            else
            {
                ed.WriteMessage((response.StatusCode).ToString());
            }
        }
    }

This my controller Post Method 这是我的控制器的Post方法

// POST: api/Checkers
    [ResponseType(typeof(Checker))]
    public IHttpActionResult PostChecker(Checker checker)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.Checkers.Add(checker);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = checker.ID }, checker);
    }

Firstly :Now i don not know what is the problem of that code to return not found Second- If there is away to build plugins in auto-cad using .net core 首先:现在,我不知道该代码返回的问题是什么?找不到第二,如果没有使用.net core在auto-cad中构建插件

Are you seeing a 404 response code? 您是否看到404响应码? Have you tried calling the api method from postman or fiddler? 您是否尝试过从邮递员或提琴手调用api方法? I'd always try calling from one of those so you can be certain the api is responding correctly. 我总是尝试从其中之一调用,以便确定api正确响应。 This will tell you whether or not the issue lies in your consuming code. 这将告诉您问题是否出在您的使用代码中。

I notice you're using PostAsJsonAsync to call the api method but the api method isn't marked as async, could that be the issue? 我注意到您正在使用PostAsJsonAsync调用api方法,但是api方法未标记为异步,这可能是问题吗?

The api method also isn't decorated with the HttpPost attribute; api方法也未使用HttpPost属性修饰; I'm not sure if that's a requirement but I'd try each of these separately 我不确定这是否有必要,但我会分别尝试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM