简体   繁体   English

ASP.NET WebAPI POST可以从Uri或Body接收参数吗?

[英]ASP.NET WebAPI can a POST receive parameters either from Uri or Body?

  1. POST /auth and write serial=123 in body POST /auth并在正文中写入serial=123
  2. POST /auth?serial=123 with an empty body POST /auth?serial=123 ,正文为空

Is it possible to accept these 2 kind of posts with one method? 是否可以用一种方法接受这两种类型的帖子?

At now I can only achieve it with 2 methods: 目前,我只能通过2种方法来实现:

[HttpPost]
public IHttpActionResult CheckSerial(string serial)

and

public class SerialViewModel
{
    public string serial { get; set; }
}
[HttpPost]
public IHttpActionResult CheckSerial(SerialViewModel sm)

I have noticed that in ASP.NET MVC5 it can be done with just one method. 我已经注意到,在ASP.NET MVC5中,仅用一种方法即可完成。

[HttpPost]
public ActionResult auth(SerialViewModel check)

I can POST either /auth (with serial=123 in body) or /auth?serial=123 . 我可以发布/auth (主体为serial=123 )或/auth?serial=123

But the WebAPI seems different? 但是WebAPI似乎有所不同?

--UPDATE-- -更新-

Inspired by comment, I find a way like this: 受评论的启发,我发现了这样的方法:

public IHttpActionResult CheckSerial(SerialViewModel sm,[FromUri]string serial = null)

And I check both of them to get a value. 我会检查它们两者以获取价值。 But this is not quite convenient, especially if there are many parameters. 但这并不是很方便,特别是在有许多参数的情况下。

Well, I think this is an acceptable way, at least for me: 好吧,我认为这是一种可接受的方式,至少对我来说:

    public IHttpActionResult CheckSerial([FromBody] SerialViewModel checkBody, [FromUri] SerialViewModel checkUri)
    {
         return Json(new { status = (checkBody?.serial ?? checkUri?.serial ?? "")=="123"?"1":"0" });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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