Web API Post 方法不起作用 [英] Web API Post Method not working

查看:65
本文介绍了Web API Post 方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 webapi 控制器,下面是一个 post 方法.

I have a webapi controller and following is a post method.

   public HttpResponseMessage Register(string email, string password)
   {

   }

如何从浏览器进行测试?

How do I test from the browser?

当我使用以下代码从浏览器测试它时,它没有击中控制器.

When I test it from the browser with the following , it is not hitting the controller.

http://localhost:50435/api/SignUp/?email=sini@gmail.com&password=sini@1234

它给了我以下错误.

无法将多个参数('id' 和 'password')绑定到请求的内容.

Can't bind multiple parameters ('id' and 'password') to the request's content.

你能帮帮我吗???

推荐答案

你得到一个错误,因为你不能通过这种方式向 WebApi 传递多个参数.

You get an error, because you cannot pass multiple parameter to WebApi in this way.

第一个选项:
您可以通过这种方式创建一个类并从 body 传递数据:

First option:
You can create a class and pass data through from body in this way:

public class Foo
{
    public string email {get;set;}
    public string password {get;set;}
}

public HttpResponseMessage Register([FromBody] Foo foo) 
{
    //do something
    return Ok();
}

第二个选项:

public HttpResponseMessage Register([FromBody]dynamic value)
{
    string email= value.email.ToString();
    string password = value.password.ToString();
}

并以这种方式传递json数据:

And pass json data in this way:

{
  "email":"abc@test.com",
  "password":"123@123"
}

更新:

如果你想从 URL 获取数据,那么你可以使用属性路由.

If you wan to get data from URL, then you can use Attribute Routing.

[Route("api/{controller}/{email}/{password}")]
public HttpResponseMessage Register(string email, string password) 
{
    //do something
    return Ok();
}

注意:
URL 应该是:http://localhost:50435/api/SignUp/sini@gmail.com/sini@1234
不要忘记在 WebApiConfig
中启用属性路由如果你使用这种方式,你会有安全问题.

这篇关于Web API Post 方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆