Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

c# - Post int as part of method but get No HTTP resource was found that matches the request URI error

I am trying to create a MVC WebAPI controller, which takes in an id, which it creates a record with in the database and then returns. However, I keep getting an error.

In my testAPI controller I have:

[HttpPost]
public HttpResponseMessage OpenSession(int id)
{
    //Logic of post in here never gets hit
}

However when I try and post to the API I get the following response:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:54388/api/testAPI/OpenSession/'.","MessageDetail":"No action was found on the controller 'testAPI' that matches the request."}

I have changed my routing to:

config.Routes.MapHttpRoute(
  name: "DefaultApi",
  routeTemplate: "api/{controller}/{action}/"
);

I am trying to post to: http://localhost:54388/api/testAPI/OpenSession/ with the value id in the payload. However I think it is expecting it in the URL - can someone please point out where I am going wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

WebApi is problematic when you try to POST only a single parameter. I remember I had the same problem. There are many ways to sort this out, but the one that works every time is to have a model instead of an int:

[HttpPost]
public HttpResponseMessage OpenSession(OpenSessionParameters parameters)
{
    //Logic of post in here never gets hit
}

public class OpenSessionParameters
{
    public int Id { get; set; }
}

Or if you insist on not having a class, you can try this: http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
I have used this for a bit, but ended up replacing all of [FromBody] arguments to models - works more reliable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...