简体   繁体   中英

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". 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: 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

Are you seeing a 404 response code? Have you tried calling the api method from postman or fiddler? I'd always try calling from one of those so you can be certain the api is responding correctly. 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?

The api method also isn't decorated with the HttpPost attribute; I'm not sure if that's a requirement but I'd try each of these separately

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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