验证查询参数没有.netcore API使用模型

问题描述 投票:2回答:4

是否有可能在一个动作验证查询参数,而无需使用模式?很多我的API的调用都是一次性的,我没有看到一个点,使他们的模型,如果他们将只使用一次。

我看到了下面的文章,这似乎就像是正是我需要的,但我不希望它返回一个404,如果需要的parm不存在,我希望它返回类似出炉的错误消息的对象在模型验证 - 真的,我只是想被视为一个模型中的参数,而实际上不必做一个模型。

https://www.strathweb.com/2016/09/required-query-string-parameters-in-asp-net-core-mvc/

[HttpPost]
public async Task<IActionResult> Post(
    [FromQueryRequired] int? Id,
    [FromQuery] string Company)

编辑: 的[FromQueryRequired]是抛出404如果ID PARM缺少(这是直接从物品截取)的自定义ActionConstraint。不过,我不希望做404,我想有一个消息,说一个对象{消息:“ID是必需的”}。我认为这个问题是我无法从动作约束中访问响应上下文。

c# asp.net-core asp.net-core-2.0
4个回答
3
投票

从Asp.Net 2.1核心有其自动做这个验证内置参数[BindRequired。

public async Task<ActionResult<string>> CleanStatusesAsync([BindRequired, 
    FromQuery]string collection, [BindRequired, FromQuery]string repository,
       [BindRequired, FromQuery]int pullRequestId)
{
    // all parameters are bound and valid
}

如果调用不带参数的这种方法,会返回一个错误的ModelState:

{
"collection": [
  "A value for the 'collection' parameter or property was not provided."
],
"repository": [
  "A value for the 'repository' parameter or property was not provided."
],
"pullRequestId": [
  "A value for the 'pullRequestId' parameter or property was not provided."
],
}

更多详情,请this excellent article找到。


2
投票

您可以从请求读取和验证它

string id= HttpContext.Request.Query["Id"].ToString();


    if (id==nll)
    {
    //do any thing here
    }

0
投票

我还没有尝试可能是这样的;

public class MyActionFilterAttribute: IActionFilter
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var id = actionContext.ActionArguments["Id"];
        if(string.IsNullOrEmpty(id))
            actionContext.Response = actionContext.Request.CreateResponse(
            HttpStatusCode.OK, 
            new {MESSAGE = "ID is required"}, 
            actionContext.ControllerContext.Configuration.Formatters.JsonFormatter
        );
    }
}

[HttpPost]
[MyActionFilterAttribute]
public ActionResult Post([FromQueryRequired] int? Id,[FromQuery] string Company)

0
投票

下面是我最终使用的解决方案。属性添加到名为[RequiredParm]的PARMS。我松散的基础在别人身上的答案不同的问题,但我似乎不能在瞬间找到它,对不住你是谁,如果我能找到它,我会更新这个答案信贷。

编辑:找到它,通过@詹姆斯法回答 - Web Api Required Parameter

用法:

[HttpPost]
public async Task<IActionResult> Post(
    [FromQuery, RequiredParm] int? Id,
    [FromQuery] string Company)

ActionFilterAttribute:

[AttributeUsage(AttributeTargets.Method)]
public sealed class CheckRequiredParmAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var requiredParameters = context.ActionDescriptor.Parameters.Where(
            p => ((ControllerParameterDescriptor)p).ParameterInfo.GetCustomAttribute<RequiredParmAttribute>() != null).Select(p => p.Name);

        foreach (var parameter in requiredParameters)
        {
            if (!context.ActionArguments.ContainsKey(parameter))
            {
                context.ModelState.AddModelError(parameter, $"The required argument '{parameter}' was not found.");
            }
            else
            {
                foreach (var argument in context.ActionArguments.Where(a => parameter.Equals(a.Key)))
                {
                    if (argument.Value == null)
                    {
                        context.ModelState.AddModelError(argument.Key, $"The requried argument '{argument.Key}' cannot be null.");
                    }
                }
            }
        }

        if (!context.ModelState.IsValid)
        {
            context.Result = new BadRequestObjectResult(context.ModelState);
            return;
        }

        base.OnActionExecuting(context);
    }
}

/// <summary>
/// Use this attribute to force a [FromQuery] parameter to be required. If it is missing, or has a null value, model state validation will be executed and returned throught the response. 
/// </summary>  
[AttributeUsage(AttributeTargets.Parameter)]
public sealed class RequiredParmAttribute : Attribute
{
}
© www.soinside.com 2019 - 2024. All rights reserved.