ASP.NET WebAPI throw 404 if method parameter is st

2019-04-26 19:39发布

I did a very simple test on ASP.NET MVC4 WebAPI and found some interesting issue:

When a method is taking complex type, it will work, but when it takes string or int, it will throw 404, as the screen shot given: The "AddProduct" works, but "Test" and "Test1" is always not found.

How should I invoke the method correctly?

Web API Code

404 when invoking the Test method

my route config

5条回答
女痞
2楼-- · 2019-04-26 20:03

You need to decorate your string or int parameter with the [FromBody] attribute.

[HttpPost] public string Test([FromBody]string username)

[HttpPost] public int Test1([FromBody]int value)

查看更多
可以哭但决不认输i
3楼-- · 2019-04-26 20:09

try this:

the website is accept the value by "[FormBody]", so you should be post by "={0}" ({0} is replaced by your string data)

$.ajax({
    url: "api/values",
    data: "='hello world'",
    dataType: "text",
    type: "POST",
    success: function (data) {
        $("#result").val(data);
    },
    fail: function (data) {
        alert(data);
    }
});

see also this answer: POST a string to Web API controller in ASP.NET 4.5 and VS 2012 RC

查看更多
4楼-- · 2019-04-26 20:21

Have you tried,

$.ajax({
  url : "/api/product/test",
  data : { username : "edi" },
  dataType : "json",
  type : "POST",
  success : function(res){ console.log(res); },
  error : function(req, stat, err){ console.log(stat + ": " + err); }
});

Right now it's failing becuase you've wrapped your entire json object (in the jquery ajax method) in quotes.

Try without the quotes and let me know!

Also,

When testing single variables like string username and int value take a note that WEB API will expect it exactly like that.

This guy,

[HttpPost]
public string Test1(int value) { ... }

Will look for a post that matches this url signature (im using HTTPIE)...

$ http POST http://yourwebsite.com/api/test1 value=1

Where the "4" is the value of the variable "value" in that Test1 method.

More about HTTPIE here: Scott Hanselman on installing HTTPIE

Hope that helps!

查看更多
欢心
5楼-- · 2019-04-26 20:22

I searched nearly a day for this because I want my data to be a JSON, so assuming you need to post one value here it is:

INT:

$.post('/api/mywebmethod', { "": 10 })

STRING

$.post('api/mywebmethod', { "": "10" });

CONTROLLER

[HttpPost]
public IHttpActionResult MyWebMethod([FromBody]int id)
{
//do work
}
查看更多
三岁会撩人
6楼-- · 2019-04-26 20:27

using Route

[RoutePrefix("api/Product")]
public class ProductController:ApiController
{
[Route("Add"),HttpPost]
public string AddProduct(Product productModel)

[Route("Test"),HttpPost]
public string Test(string userName){}
}

call: localhost:xx//api/product/Add

查看更多
登录 后发表回答