简体   繁体   English

重用ASP.NET Web API项目中的公共资源参数

[英]Reuse common resource parameters within ASP.NET Web API project

What is the best approach to reuse the type and name of common resource parameters within an ASP.NET Web API project? 在ASP.NET Web API项目中重用公共资源参数的类型和名称的最佳方法是什么? Some examples: 一些例子:

public HttpResponseMessage GetObjects(int rpp, int page, string q, string include)
{
    ...
}

Could be implemented as: 可以实现为:

public HttpResponseMessage GetObjects([FromUri] CustomParameterModel)
{
    ...
}

public CustomParameterModel
{
    // results per page
    public int rpp { get; set; }

    // current page
    public int page { get; set; }

    // search terms
    public string q { get; set; }

    // include defined properties
    public string include { get; set; }
}

Both approaches described above results in the following URL: objects?rpp={rpp}&page={page}&q={q}&include={include} 上述两种方法均产生以下URL:objects?rpp = {rpp}&page = {page}&q = {q}&include = {include}

This is fine for the objects resource, but not for the files resource for example. 例如,这对对象资源很好,但对文件资源来说不是。 The files resource does not need the include parameter. 文件资源不需要include参数。

public HttpResponseMessage GetFiles(int rpp, int page, string q)
{
    ...
}

How could this be achieved in an elegant way without rewriting the type and name of the parameters? 如何在不重写参数类型和名称的情况下以一种优雅的方式实现这一目标?

I think you could write own model binder ( http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api ) which will serve that for you. 我认为您可以编写自己的模型绑定程序( http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api )您。

Another approach would be to write message handler which could pre process requests ( http://www.asp.net/web-api/overview/working-with-http/http-message-handlers ) and validate your parameters (assign default values etc). 另一种方法是编写消息处理程序,该消息处理程序可以预处理请求( http://www.asp.net/web-api/overview/working-with-http/http-message-handlers )并验证参数(分配默认值)等等)。

Finally, if you do not mark fields as required ( http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api ) they could leave with default values, for yours that could be 0 for int or null for int? 最后,如果您未按要求将字段标记为( http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api ),它们可能会离开带有默认值,对于您来说可以为0或int? and null for string. 字符串为null。

It is always about the particular case, try different approaches and find best which fits to your needs. 它始终是针对特定情况的,尝试不同的方法并找到最适合您需求的方法。

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

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