GVKun编程网logo

c# – 在WebApi服务中使用[FromUri]属性忽略DataMember的Name属性

31

如果您想了解c#–在WebApi服务中使用[FromUri]属性忽略DataMember的Name属性的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于4.1函数的name属性、asp.ne

如果您想了解c# – 在WebApi服务中使用[FromUri]属性忽略DataMember的Name属性的相关知识,那么本文是一篇不可错过的文章,我们将为您提供关于4.1函数的name属性、asp.net-mvc – Web API可空的必需属性需要DataMember属性、asp.net-web-api – 在Webapi中使用Url.Link与属性路由2、AWS Apigateway 如何把 url path parameter 传递到后端 lambda 的 pathParameter 中 (From Chatgpt)的有价值的信息。

本文目录一览:

c# – 在WebApi服务中使用[FromUri]属性忽略DataMember的Name属性

c# – 在WebApi服务中使用[FromUri]属性忽略DataMember的Name属性

我们正在使用Asp.Net WebApi创建RestService.但是由于某些原因,在尝试使用[FromURI]属性反序列化复杂属性时,DataMember属性中的Name属性被忽略.

例如我们可能有:
方法:

public IHttpActionResult Get([FromUri]User user)

模型:

[DataContract]
public class User
{
    [DataMember(Name = "username")]
    public string Username{ get; set; }
    [DataMember(Name = "isActive",Isrequired = false)]
    public bool? Active { get; set; }
}

反序列化用户时,我们按预期获取用户名,但对于Active为null.另一方面,当序列化数据时,我们同时获得了isActive和用户名.如果我们发送查询字符串中的活动请求,它按预期工作.

这显然是IModelBinder的问题.由于某些原因,它不使用DataMember的Name属性.我检查了什么格式化器被包括和4个默认的注册:

System.Net.Http.Formatting.JsonMediaTypeFormatter
System.Net.Http.Formatting.XmlMediaTypeFormatter
System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter
System.Net.Http.Formatting.JQueryMvcFormUrlEncodedFormatter

我没有办法根据要求检查哪一个.我会假设它的FormUrlEncodedMediaTypeFormatter但我不能确定.另外,我不知道如果它甚至支持Name属性.

我已经检查了一个解决方案和最接近的主题,我可以找到是WebAPI DataMember Name not used when de/serializing via application/x-www-form-urlencoded,但它不使用[FromUri]但应用程序/ x-www-form-urlencoded属性,它没有真正解决.

任何想法,指点或建议将不胜感激.

解决方法

您必须检查您的“获取”请求.你的请求必须是这样的;
GET api/foo?username=fooname&active=false

您不需要DataContract和DataMember属性才能实现此目的.这些属性只是为了另一件事情,它不是使用的主要原因.

获得有效的get方法后,在你的方法,你可以检查modelstate像;

if (ModelState.IsValid) {
/// your code goes here    
}

4.1函数的name属性

4.1函数的name属性

关于函数name属性,不同声明方式有所差异,没有规律只能硬记

 

asp.net-mvc – Web API可空的必需属性需要DataMember属性

asp.net-mvc – Web API可空的必需属性需要DataMember属性

我在Web API Post操作中收到以下VM
public class viewmodel
{
    public string Name { get; set; }

    [required]
    public int? Street { get; set; }
}

当我发帖时,我会收到以下错误:

Property ‘Street’ on type ‘viewmodel’ is invalid. Value-typed properties marked as [required] must also be marked with [DataMember(Isrequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(Isrequired=true)].

似乎错误是清楚的,所以我只是想要完全确定需要使用[DataContract]和[DataMember]属性,当你有一个需要可空属性的类。

有没有办法避免在Web API中使用这些属性?

解决方法

我正在面对同样的问题,我认为这是完整的废话。使用值类型,我可以看到[必需]不起作用,因为值类型的属性不能为空,但是当您具有可空值类型时,不应该有任何问题。然而,Web API模型验证逻辑似乎以相同的方式处理非可空和可空值类型,因此您必须解决它。我在 Web API forum中找到了一个解决方案,可以确认它的工作原理:创建一个ValidationAttribute子类,并将其替换为对可空值类型属性的requiredAttribute:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

public class NullablerequiredAttribute : ValidationAttribute,IClientValidatable
{
    public bool AllowEmptyStrings { get; set; }

    public NullablerequiredAttribute()
        : base("The {0} field is required.")
    {
        AllowEmptyStrings = false;
    }

    public override bool IsValid(object value)
    {
        if (value == null)
            return false;

        if (value is string && !this.AllowEmptyStrings)
        {
            return !string.IsNullOrWhiteSpace(value as string);
        }

        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata Metadata,ControllerContext context)
    {
        var modelClientValidationRule = new ModelClientValidationrequiredRule(FormatErrorMessage(Metadata.displayName));
        yield return modelClientValidationRule;
    }
}

NullablerequiredAttribute正在使用中:

public class Model
{
    [Nullablerequired]
    public int? Id { get; set; }
}

asp.net-web-api – 在Webapi中使用Url.Link与属性路由2

asp.net-web-api – 在Webapi中使用Url.Link与属性路由2

我想在使用webapi 2时向我的http响应添加一个Location头。下面的方法显示了如何使用一个命名的路由。有谁知道你是否可以使用作为webapi 2的一部分发布的属性路由功能创建Url.Link?
string uri = Url.Link("DefaultApi",new { id = reponse.Id });
httpResponse.Headers.Location = new Uri(uri);

提前致谢

解决方法

当使用属性路由时,您可以使用RouteName与Ur.Link。
public class BooksController : ApiController
{
    [Route("api/books/{id}",Name="GetBookById")]
    public BookDto GetBook(int id) 
    {
        // Implementation not shown...
    }

    [Route("api/books")]
    public HttpResponseMessage Post(Book book)
    {
        // Validate and add book to database (not shown)

        var response = Request.CreateResponse(HttpStatusCode.Created);

        // Generate a link to the new book and set the Location header in the response.
        string uri = Url.Link("GetBookById",new { id = book.BookId });
        response.Headers.Location = new Uri(uri);
        return response;
    }
}

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#route-names

AWS Apigateway 如何把 url path parameter 传递到后端 lambda 的 pathParameter 中 (From Chatgpt)

AWS Apigateway 如何把 url path parameter 传递到后端 lambda 的 pathParameter 中 (From Chatgpt)

在 AWS API Gateway 中,URL 路径参数可以通过设置 Integration Request 的 Mapping Templates 来传递到后端 Lambda 函数的 pathParameter 中。以下是具体的步骤:

1. 登录到 AWS 管理控制台,导航到 API Gateway 服务。

2. 找到您的 API,并在左侧导航栏中选择 "Resources"。

3. 在资源列表中,选择需要配置 URL 路径参数的资源,并在该资源下选择需要配置的 HTTP 方法(例如 GET 或 POST)。

4. 在您选择的 HTTP 方法下,展开 “Integration Request” 部分。

5. 在 “Integration Request” 部分,找到 “Mapping Templates” 并点击 “Add mapping template”。

6. 在弹出的对话框中,输入媒体类型(Media Type),以指定请求的 Content-Type。通常情况下,可以输入 `application/json`,或者根据您的实际需要指定适当的 Content-Type。

7. 在模板编辑器中,输入请求转换模板以将 URL 路径参数传递到后端 Lambda 的 pathParameter 中。以下是一个示例模板,用于将路径参数 `{userId}` 传递到 Lambda 函数的 pathParameter 中:

```json
{
  "pathParameters": {
    "userId": "$input.params(''userId'')"
  }
}
```

在上面的示例中,我们使用 Velocity 模板语法来从 URL 路径参数 `userId` 中提取值,并将其放入 JSON 对象的 `pathParameters` 字段中,并使用 `userId` 作为属性名。

8. 点击 “Save” 保存模板。

9. 配置完成后,点击 “Deploy API” 来部署您的 API 更改。

完成上述步骤后,当 API Gateway 收到请求时,它将使用配置的 Mapping Template 将 URL 路径参数传递到后端的 Lambda 函数的 pathParameter 中。在您的 Lambda 函数中,可以通过事件对象(event)来访问 pathParameter 的值。例如,如果您使用 Node.js 编写 Lambda 函数,可以通过 `event.pathParameters.userId` 来访问路径参数 `userId` 的值。

请注意,Mapping Templates 中的模板语法使用的是 Velocity 模板语法。确保您的模板正确处理路径参数,并将其传递给后端 Lambda 函数的 pathParameter。

关于c# – 在WebApi服务中使用[FromUri]属性忽略DataMember的Name属性的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于4.1函数的name属性、asp.net-mvc – Web API可空的必需属性需要DataMember属性、asp.net-web-api – 在Webapi中使用Url.Link与属性路由2、AWS Apigateway 如何把 url path parameter 传递到后端 lambda 的 pathParameter 中 (From Chatgpt)等相关内容,可以在本站寻找。

本文标签: