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

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

问题描述

我有一个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.

第一个选项:
您可以通过以下方式创建一个类并从主体传递数据:

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();
}

注意:
网址应为:http://localhost:50435/api/SignUp/sini@gmail.com/sini@1234
不要忘记在WebApiConfig
中启用属性路由 如果使用这种方式,则会遇到安全问题.

Note:
URL should be : http://localhost:50435/api/SignUp/sini@gmail.com/sini@1234
Don't forget to enable attribute routing in WebApiConfig
If you use this way, you will have security issue.

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

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