简体   繁体   English

如何将Swagger与来自Web API操作方法的动态参数一起使用?

[英]How do I use Swagger with dynamic parameters from a Web API Action Method?

I write my Web API controllers in a non-standard way where I get the parameters as dynamic objects. 我以非标准的方式编写Web API控制器,在其中我将参数作为动态对象获取。

This creates an issue with NSwag. 这会引起NSwag问题。 Because there are no parameters in the method definition, NSwag cannot generate what is needed. 由于方法定义中没有参数,因此NSwag无法生成所需的内容。

I wonder if there is any option to use NSwag in this situation. 我想知道在这种情况下是否可以使用NSwag。 Maybe there are some attributes that I can add to the methods so that NSwag will be able to generate the API? 也许有些属性可以添加到方法中,以便NSwag能够生成API?

[HttpPost]
[ActionName("create-account")]
public IHttpActionResult CreateAccount()
{
    var body = Request.Content.ReadAsStringAsync().Result;

    dynamic json = Utils.GetJsonBody(body);

    if (!Utils.GetJsonPropertyValueByPropertyName<String>(json, "email", out String email))
    {
        return Content(HttpStatusCode.BadRequest, "Please provide a valid email.".AsApiMessageResult());
    }

    if (!Utils.GetJsonPropertyValueByPropertyName<String>(json, "name", out String name))
    {
        return Content(HttpStatusCode.BadRequest, "Please provide an account name.".AsApiMessageResult());
    }

    if (!Utils.GetJsonPropertyValueByPropertyName<String>(json, "domain", out String domain))
    {
        return Content(HttpStatusCode.BadRequest, "Please provide a valid domain.".AsApiMessageResult());
    } 

The thing about Swagger is that it uses the signatures of your method to generate its documentation of how your code works. 关于Swagger的事情是,它使用方法的签名来生成其代码工作方式的文档。 Bypassing all the normal Web API and choosing to read the raw HTTP request means that Swagger can't see what you're doing, making it difficult for it to automatically determine what your code does. 绕过所有普通的Web API并选择读取原始的HTTP请求意味着Swagger无法看到您在做什么,这使其很难自动确定您的代码在做什么。 The technique you're doing with reading the raw request and using dynamic has a number of other disadvantages. 您在读取原始请求和使用动态数据时所采用的技术还有许多其他缺点。

  • You don't get Intellisense for your objects 您不会为您的对象获得Intellisense
  • It's not functional meaning it's harder to tell by looking at the method what it takes as input and output, which makes it harder to understand 它不是功能性的,这意味着很难通过查看方法来判断输入和输出的含义,这使得理解起来更加困难
  • It's harder to unit test your code, because now you have to build up an HTTP request for your Web API controller 很难对代码进行单元测试,因为现在您必须为Web API控制器建立HTTP请求
  • It requires more code than doing things with proper objects 它需要比使用适当的对象处理更多的代码

Instead, we should define a proper model to post to our API. 相反,我们应该定义一个适当的模型来发布到我们的API。 This will allow Web API to do its job, the model binder will handle converting the request into an instance of CreateAccountRequest. 这将使Web API能够完成其工作,模型绑定程序将处理将请求转换为CreateAccountRequest实例的过程。

public class CreateAccountRequest
{
    public string Email { get; set; }

    public string Name { get; set; }

    public string Domain { get; set; }
}

Then we can have our action method take this an instance of this class as a parameter. 然后,我们可以让我们的操作方法将这个类的实例作为参数。

[HttpPost]
[ActionName("create-account")]
public IHttpActionResult CreateAccount(CreateAccountRequest request)
{
    //now here you can validate the request if you want
}

Swagger should be able to understand this method now, allowing NSwag to generate a useful client. Swagger现在应该能够理解此方法,从而允许NSwag生成有用的客户端。

Note that instead of doing custom C# validation, you should look into the built in tools that Web API provides for model validation . 请注意,您应该研究Web API为模型验证提供的内置工具,而不是执行自定义C# 验证 Then all you would need to do is check the ModelState, rather than manually checking each parameter. 然后,您所需要做的就是检查ModelState,而不是手动检查每个参数。 Other tooling can also look at the attributes of your models, enhancing the tooling experience. 其他工具也可以查看模型的属性,从而改善工具体验。

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

相关问题 如何通过验证将 JSON 正文属性映射为 .NET Core Web API 操作方法的动态参数? - How can I map JSON body properties as dynamic parameters of a .NET Core web API action method with validation? 如何在autofac的RegisterGeneric()方法中使用动态参数? - How do I use dynamic parameters with autofac's RegisterGeneric() method? 如何在Web API中使用Dictionary作为带有GET方法的参数? - How do I use Dictionary as a parameter with the GET method in Web API? 如何委派动态方法名称和动态参数的调用 - How do I delegate calling of dynamic method names and dynamic parameters 如何在返回IHttpActionResult时对web api动作方法进行单元测试? - How do I unit test web api action method when it returns IHttpActionResult? 如何在 Swagger for .Net Core Web Api 中覆盖描述“无参数”? - How to override description 'No parameters' in Swagger for .Net Core Web Api? 如何从post方法接收Web API控制器中的参数? - How to receive parameters in Web API controller from post method? ASP.NET Web API操作方法参数的依赖注入 - Dependency injection for ASP.NET Web API action method parameters 如何像Web API 2一样声明MVC 5操作? - How do I declare an MVC 5 action like in Web API 2? 如何在Web API查询字符串中将多个参数作为OR处理? - How do I handle multiple parameters as an OR in a Web API querystring?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM